How to detect if a user uploaded a file larger than post_max_size?

后端 未结 6 1370
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 12:00

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

In my configuration post_max_size is a few MB

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 12:26

    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;
    }
    
    

    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.)

    --

    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.

提交回复
热议问题