我正在处理一个PHP表单,该表单将一个文件附加到电子邮件中,并尝试优雅地处理上传的文件太大的情况。
我了解到php.ini
中有两个设置会影响文件上传的最大大小:upload_max_filesize
和post_max_size
。
如果一个文件的大小超过了upload_max_filesize
,PHP会返回该文件的大小为0。这很好;我可以检查一下。
但是如果它超过了post_max_size
,我的脚本就会默默地失败,并返回到空白表单。
有什么方法可以捕捉到这个错误吗?
发布于 2010-01-26 00:24:54
如果post数据的大小大于post_max_size,则$_POST和$_FILES超全局变量为空。这可以通过各种方式进行跟踪,例如,通过将$_GET变量传递给处理数据的脚本,即检查是否设置了$GET‘’processed‘。
因此,不幸的是,PHP看起来不会发送错误。由于它发送的是一个空的$_POST数组,这就是为什么你的脚本返回到空白表单-它不认为这是一个帖子。(一个相当糟糕的设计决策IMHO)
This commenter还有一个有趣的想法。
似乎更优雅的方法是比较post_max_size和$_SERVER‘’CONTENT_LENGTH‘。请注意,后者不仅包括上传文件的大小加上帖子数据,还包括多部分序列。
发布于 2011-07-24 17:06:12
有一种方法可以捕获/处理超过最大post大小的文件,这是我的首选,因为它会告诉最终用户发生了什么以及谁出了错;)
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...
addForm(); //bounce back to the just filled out form.
}
else {
// continue on with processing of the page...
}
发布于 2014-06-13 17:44:52
我们得到了SOAP请求的问题,其中检查$_POST和$_FILES的空性不起作用,因为它们在有效的请求中也是空的。
因此,我们实现了一个检查,比较了CONTENT_LENGTH和post_max_size。抛出的异常稍后由我们注册的异常处理程序转换为XML-SOAP-FAULT。
private function checkPostSizeExceeded() {
$maxPostSize = $this->iniGetBytes('post_max_size');
if ($_SERVER['CONTENT_LENGTH'] > $maxPostSize) {
throw new Exception(
sprintf('Max post size exceeded! Got %s bytes, but limit is %s bytes.',
$_SERVER['CONTENT_LENGTH'],
$maxPostSize
)
);
}
}
private function iniGetBytes($val)
{
$val = trim(ini_get($val));
if ($val != '') {
$last = strtolower(
$val{strlen($val) - 1}
);
} else {
$last = '';
}
switch ($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
// fall through
case 'm':
$val *= 1024;
// fall through
case 'k':
$val *= 1024;
// fall through
}
return $val;
}
https://stackoverflow.com/questions/2133652
复制相似问题