PHP上傳檔案會受限於 php.ini post_max_size 的值,這非常合理,但在程式中檔案上傳超過 post_max_size 時會直接中斷檔案上傳動作,吐出一個Warning :
Warning: POST Content-Length of 60142169 bytes exceeds the limit of 52428800 bytes in Unknown on line 0
在正式環境中,通常會關閉錯誤報告,程式中試著用 $_POST and $_FILES 找上傳檔案超出 post_max_size 的線索,皆回傳空值,如此一來程式很難判斷發生了怎麼一回事,沒辦法回應使用者目前情況,影響使用者體驗
透過以下代碼,可以透過PHP判斷上傳檔案超出 post_max_size 的錯誤,以便在輸出的頁面告訴使用者發生什麼事,當然也可以修改它,做需要的錯誤處裡
/**
* 獲取上傳檔案超過 PHP.ini post_max_size 錯誤訊息
* @since 1.01.29
* @link https://vector.cool
*/
if (empty($_FILES) && empty($_POST) &&
isset($_SERVER['REQUEST_METHOD']) &&
strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
//catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!<br>Please be advised this is not a limitation in the CMS, This is a limitation of the hosting server.<br>For various reasons they limit the max size of uploaded files, if you have access to the php ini file you can fix this by changing the post_max_size setting.<br> If you can't then please ask your host to increase the size limits, or use the FTP uploaded form</p>"; // echo out error and solutions...
}
else {
// continue on with processing of the page...
}