如何捕捉此错误?(POST内容长度..)


How can I catch this error? (POST Content-Length ...)

上传图像时,我收到以下错误:(一张图像最多8mb)

Warning: POST Content-Length of 14259306 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

如何按惯例显示此消息?我的意思是,我想把这个错误放在CSS样式中。非常感谢。

也许你想试试这样的东西。

if (isset($_SERVER["CONTENT_LENGTH"])) {
    if ($_SERVER["CONTENT_LENGTH"] > ((int)ini_get('post_max_size') * 1024 * 1024)) {
        die('<script type="text/javascript">window.open("some page youre gonna handle the error","_self");</script>');
    }
}

如果出现常见错误,需要设置错误处理程序。请参阅此处了解详细信息但是

如果在脚本执行之前发生错误(例如,在文件上传时)无法调用自定义错误处理程序,因为它未注册当时。

if ($_SERVER['CONTENT_LENGTH'] < 8380000) {
 ... your code
} else {
    ... Your Error Message
}

您也可以增加php.ini 中的最大大小

post_max_size = 60M
upload_max_filesize = 60M

使用@Batu Zet的答案来检查代码,然后确保php.ini文件中的display_errors已关闭:

display_errors=Off

您可以通过两种方式限制上传文件的最大大小:

  1. 以HTML形式包含<input type="hidden" name="MAX_FILE_SIZE" value="..." />
  2. 在php.ini中设置upload_max_filesize

如果您试图上传大于upload_max_filesize的文件,在PHP脚本运行之前,PHP将发出这样的警告:

警告:POST内容长度14259306字节超过限制第0行上未知8388608字节

在这种情况下,CCD_ 7和CCD_。UPLOAD_ERR_INI_SIZE永远不会工作。不管怎样,我从来没有在代码中发现过它。

当上传的文件小于upload_max_filesize时,$_FILES数组的某些元素可能包含大于MAX_FILE_SIZE的文件的UPLOAD_ERR_FORM_SIZE错误代码。

您可以通过下一个PHP脚本捕捉到这两种情况:

<?php
$warning = error_get_last();
if ($warning !== null && stripos($warning['message'], 'POST Content-Length of') !== false) {
  error_clear_last();
  echo 'Upload is bigger than '.ini_get('upload_max_filesize');
}
else if ($_FILES['input_name']['error'] == UPLOAD_ERR_FORM_SIZE) {
  echo 'Upload is bigger than '.$_POST['MAX_FILE_SIZE'];
}

在TRY/CATCH中包装上传。捕捉错误并在Catch中进行处理。

try {
    :: file upload ::
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "'n";
}