大檔上傳失敗常見原因:php.ini 限制、Web Server 客戶端 Body 限制、腳本執行超時。本文系統整理三層配置、修改方式、驗證方法。
| 參數 | 預設 | 建議大檔值 | 說明 |
|---|---|---|---|
upload_max_filesize | 2M | 100M | 單檔最大 |
post_max_size | 8M | 150M | 整個 POST Body 最大,**必須 > upload_max_filesize** |
max_execution_time | 30s | 0 (無限制) 或 300 | 腳本最大執行秒數,大檔需更久 |
max_input_time | 60s | 300 | 解析輸入資料最大秒數 |
memory_limit | 128M | 256M+ | 腳本記憶體上限,處理大檔可能需更多 |
# 1. 找到 php.ini php --ini # 2. 編輯 upload_max_filesize = 100M post_max_size = 150M max_execution_time = 300 max_input_time = 300 memory_limit = 256M # 3. 重載 PHP-FPM / Apache systemctl reload php-fpm # 或 Apache systemctl reload httpd
<?php
// 僅能調小,不能調大 upload_max_filesize/post_max_size
ini_set('max_execution_time', '300');
// .user.ini (PHP 5.3+,針對目錄)
upload_max_filesize = 100M
post_max_size = 150M
# .htaccess (Apache + mod_php)
php_value upload_max_filesize 100M
php_value post_max_size 150M
http {
client_max_body_size 150M; # 預設 1M,必須調大
}
# 或 server/location 區塊
server {
client_max_body_size 150M;
}
# httpd.conf 或 .htaccess LimitRequestBody 157286400 # 150M = 150*1024*1024 bytes # 注意:LimitRequestBody 單位是 bytes
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="104857600"> <!-- 100MB,瀏覽器端攔截(可繞過) -->
<input type="file" name="file">
<button type="submit">上傳</button>
</form>
php -i | grep -E 'upload_max_filesize|post_max_size|max_execution_time' 確認生效。nginx -T | grep client_max_body_size 確認生效。$_FILES['file']['error']:| 錯誤碼 | 常見原因 |
|---|---|
| UPLOAD_ERR_INI_SIZE | 超過 upload_max_filesize |
| UPLOAD_ERR_FORM_SIZE | 超過表單 MAX_FILE_SIZE |
| UPLOAD_ERR_PARTIAL | 上傳中斷(網路/超時) |
| 413 Request Entity Too Large | Nginx/Apache 攔截 |
| 504 Gateway Timeout | 上傳時間超過 proxy_read_timeout |
「PHP.ini → Web Server → 前端」三層限制缺一不可。大檔上傳必須分片/直傳/非同步,單一請求上傳 GB 級檔案在生產環境不可行。