首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 檔案上傳大小限制完整設定指南:php.ini、.htaccess、ini_set 三種方式詳解

     編輯:PHP 綜合知識

上傳大小相關的 PHP 設定參數

參數說明預設值建議值
file_uploads啟用 HTTP 檔案上傳OnOn
upload_tmp_dir暫存目錄(需寫入權限)系統預設自訂目錄
upload_max_filesize單一檔案上傳上限2M10M~100M
post_max_sizePOST 總資料上限(需 > upload_max_filesize)8M12M~128M
max_input_time接收資料最大秒數6090~300
max_execution_time腳本執行最大秒數30180~600
memory_limit腳本記憶體上限(需 > post_max_size)128M256M~512M

三種修改方式優劣比較

1. php.ini(永久、全域,需重啟 PHP-FPM/Apache)

file_uploads = On
upload_max_filesize = 10M
post_max_size = 12M
max_input_time = 90
max_execution_time = 180
memory_limit = 20M

優點:生效範圍最廣、永久有效。缺點:需伺服器管理權限、修改後需重啟服務。

2. .htaccess(目錄層級,Apache 需 AllowOverride All)

php_value upload_max_filesize 10M
php_value post_max_size 12M
php_value max_input_time 90
php_value max_execution_time 180
php_value memory_limit 20M

適用:虛擬主機、無 php.ini 權限但支援 .htaccess 的環境。

3. ini_set()(執行期、當前腳本,部分參數無效)

<?php
ini_set('file_uploads', 'On');
ini_set('max_input_time', '90');
ini_set('max_execution_time', '180');
ini_set('post_max_size', '12M');      // 無效!屬於 PHP_INI_PERDIR
ini_set('upload_max_filesize', '10M'); // 無效!屬於 PHP_INI_PERDIR
ini_set('memory_limit', '20M');        // 安全模式下可能無效
?>

關鍵限制:upload_max_filesize、post_max_size 屬於 PHP_INI_PERDIR,**無法用 ini_set() 修改**,只能在 php.ini、.htaccess、httpd.conf 設定。僅 PHP_INI_ALL 類別參數才支援 ini_set()。

驗證設定是否生效

<?php
echo 'file_uploads: ' . ini_get('file_uploads') . "\n";
echo 'max_input_time: ' . ini_get('max_input_time') . "\n";
echo 'max_execution_time: ' . ini_get('max_execution_time') . "\n";
echo 'post_max_size: ' . ini_get('post_max_size') . "\n";
echo 'upload_max_filesize: ' . ini_get('upload_max_filesize') . "\n";
echo 'memory_limit: ' . ini_get('memory_limit') . "\n";
?>

常見問題排查

  • Nginx + PHP-FPM:另需設定 client_max_body_size 20M; 在 nginx.conf http 或 server 區塊。
  • 安全模式:safe_mode = On 時 ini_set() 受限,建議關閉安全模式(PHP 5.4+ 已移除)。
  • 上傳失敗無錯誤:檢查 $_FILES['file']['error'],1 = 超過 upload_max_filesize,2 = 超過 MAX_FILE_SIZE 隱藏欄位。
  • 大檔案斷點續傳:需前端分片 + 後端合併,單純調大上限無法解決網路中斷問題。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved