如何优雅地处理超过 PHP `post_max_size` 的文件?

2022-01-09 00:00:00 upload php

我正在开发一个将文件附加到电子邮件的 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_filesizepost_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 变量传递给处理数据的脚本,即 <formaction="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)

这个评论者也有一个有趣的想法.

似乎更优雅的方式是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.

相关文章