如何检测用户上传的文件是否大于 post_max_size?

2021-12-24 00:00:00 file-upload php php-5.3

我应该如何以理智的方式处理超过 post_max_size 的 http 上传?

How should I go about handling http uploads that exceeds the post_max_size in a sane manner?

在我的配置中 post_max_sizeupload_max_filesize 大几 MB我遇到的问题是:
如果用户上传的文件超过 post_max_size

In my configuration post_max_size is a few MB larger than upload_max_filesize The problems I'm having are:
If a user uploads a file exceeding post_max_size

  • _POST 数组为空
  • _FILES 数组为空,当然其中不存在任何错误代码.
  • 没有其他信息可以通过这些方式访问什么样的表单帖子.

部分问题在于接收脚本根据 POST 的内容采取不同的操作.

Part of the problem is that the receiving script takes different actions depending on the contents of the POST.

我确实可以访问 _SERVER 变量并且可以获得关于发生了什么的线索,即 CONTENT_TYPECONTENT_LENGTHREQUEST_METHOD.然而,根据这些内容进行猜测似乎很成问题.

I do have access to the _SERVER variables and can get clues as to what happened, i.e. CONTENT_TYPE, CONTENT_LENGTH and REQUEST_METHOD. It does however seem very problematic to make guesses based on those contents.

MEMORY_LIMIT(设置为相关大小的 10 倍)和 Apaches LimitRequestBody(设置为无限制)没有问题.

MEMORY_LIMIT (set to 10 times the relevant sizes) and Apaches LimitRequestBody (set to unlimited) are found to not be at fault.

就目前而言,我什至很难向用户提供任何有意义的信息.

As it stands now I have a hard time even providing any meaningful messages to the user.

有什么办法可以保留一些表单数据,以便更好地了解发生了什么问题?我非常不愿意离开 php.

Is there any way to retain some form data to get better clues as to what has gone wrong? I'm very reluctant to move away from php.

推荐答案

对于不需要服务器端更改的简单修复,我将使用 HTML5 文件 API 在上传之前检查文件的大小.如果超过已知限制,则取消上传.我相信这样的事情会奏效:

For a simple fix that would require no server side changes, I would use the HTML5 File API to check the size of the file before uploading. If it exceeds the known limit, then cancel the upload. I believe something like this would work:

function on_submit()
{
  if (document.getElementById("upload").files[0].size > 666)
  {
    alert("File is too big.");
    return false;
  }

  return true;
}

<form onsubmit="return on_submit()">
<input id="upload" type="file" />
</form>

显然这只是一个例子的骨架,并不是每个浏览器都支持这个.但是使用它不会有什么坏处,因为它可以以这样一种方式实现,它可以优雅地降级为旧浏览器的任何东西.

Obviously it's just a skeleton of an example, and not every browser supports this. But it wouldn't hurt to use this, as it could be implemented in such a way that it gracefully degrades into nothing for older browsers.

当然,这并不能解决问题,但它至少可以让您的一些用户以最少的努力感到满意.(他们甚至不必等待上传失败.)

Of course this doesn't solve the issue, but it will at least keep a number of your users happy with minimal effort required. (And they won't even have to wait for the upload to fail.)

--

顺便说一句,检查 $_SERVER['CONTENT_LENGTH'] 与帖子和文件数据的大小可能有助于检测是否有问题.我认为当出现错误时它不会为零,而 $_POST$_FILES 都是空的.

As an aside, checking $_SERVER['CONTENT_LENGTH'] vs the size of the post and file data might help detect if something failed. I think it when there is an error it will be non zero, while the $_POST and $_FILES would both be empty.

相关文章