如何优雅地处理超过PHP的`post_max_size`的文件? [英] How to gracefully handle files that exceed PHP's `post_max_size`?
问题描述
我正在处理一个将文件附加到电子邮件的PHP表单,并试图妥善处理上传的文件太大的情况.
I'm working on a PHP form that attaches a file to an email, and trying to gracefully handle cases where the uploaded file is too large.
我了解到php.ini
中有两个设置会影响文件上传的最大大小:upload_max_filesize
和post_max_size
.
I've learned that there are two settings in php.ini
that affect the maxiumum size of a file upload: upload_max_filesize
and post_max_size
.
如果文件大小超过upload_max_filesize
,PHP将返回文件大小为0.我可以检查一下.
If a file's size exceeds upload_max_filesize
, PHP returns the file's size as 0. That's fine; I can check for that.
但是,如果超过post_max_size
,我的脚本会静默失败,然后返回空白表格.
But if it exceeds post_max_size
, my script fails silently and goes back to the blank form.
有什么方法可以捕获此错误?
推荐答案
来自
如果发布数据的大小更大
比post_max_size, $ _ POST和
$ _FILES个超级全局变量为空.这
可以通过各种方式进行跟踪,例如
通过将$ _GET变量传递给
脚本处理数据,即< form
action ="edit.php?processed = 1">,以及
然后检查$ _GET ['processed']是否
设置.
If the size of post data is greater
than post_max_size, the $_POST and
$_FILES superglobals are empty. This
can be tracked in various ways, e.g.
by passing the $_GET variable to the
script processing the data, i.e. <form
action="edit.php?processed=1">, and
then checking if $_GET['processed'] is
set. 因此,不幸的是,PHP似乎没有发送错误.并且由于它发送了一个空的$ _POST数组,这就是为什么脚本返回空白格式的原因-它不认为它是POST. (恕我直言,这是一个糟糕的设计决策) So unfortunately, it doesn't look like PHP sends an error. And since it sends am empty $_POST array, that is why your script is going back to the blank form - it doesn't think it is a POST. (Quite a poor design decision IMHO) 此评论者也有一个有趣的想法. This commenter also has an interesting idea. 似乎更优雅的方法是
post_max_size与之间的比较
$ _SERVER ['CONTENT_LENGTH'].请
请注意,后者不仅包括
上传文件的大小加上发布数据
还有多部分序列. It seems that a more elegant way is
comparison between post_max_size and
$_SERVER['CONTENT_LENGTH']. Please
note that the latter includes not only
size of uploaded file plus post data
but also multipart sequences. 这篇关于如何优雅地处理超过PHP的`post_max_size`的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!