How can I limit users from uploading more then 5MB

2019-08-11 13:39发布

I have a check in place via php to determine if the file is to big, the problem is, user has to upload the file to the server first, before i can make the check.

So if someone wanted to waste my bandwidth, all they woudl have to do is rename a huge file to .jpg for example and upload it. And there is nothing i can do to stop them

There must be some way to prevent this. Some kind of a valid check or jquery or something.

I need a solution that would allow me to notify the user that the file he is trying to upload is too big.

Thanks.

3条回答
家丑人穷心不美
2楼-- · 2019-08-11 14:00

You can use this hidden feature : MAX_FILE_SIZE

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.

details : http://php.net/manual/en/features.file-upload.post-method.php

查看更多
唯我独甜
3楼-- · 2019-08-11 14:04

You can limit the max upload size as a PHP setting. The user will still be able to upload up to that size though until the server cancels, and he will not necessarily know the file is too big beforehand.

I suggest you to look into HTML features. See MDN https://developer.mozilla.org/en/using_files_from_web_applications

With it you can check size etc with JavaScript.

查看更多
你好瞎i
4楼-- · 2019-08-11 14:09

If you're concerned about wasting bandwidth, then you must handle this at a higher level in your server stack. By the time PHP is handling the file it's too late, the upload has already occurred and the bandwidth consumed.

Apache has some configuration directives that may be useful:

http://httpd.apache.org/docs/current/mod/core.html#limitrequestbody

But I'm not sure if even that actually cuts off the request when the body exceeds the limit. If not, you'd have to move up yet another level and handle it at the TCP level.

If you do want to go down a non-PHP route to try to block large uploads, you should ask on ServerFault instead of StackOverflow.

查看更多
登录 后发表回答