简体   繁体   English

如何在PHP中限制文件上传大小?

[英]How to limit file upload size in PHP?

I want to save bandwidth and restrict the size of uploaded files to our webpage. 我想节省带宽并将上传文件的大小限制在我们的网页上。 The problem is that I can set the maximal size of uploaded file (eg, 1 MB) but a user can select 50 MB file and can upload it to find out that PHP really doesn't accept files of this size -- the uploading is totally unnecessary. 问题是我可以设置上传文件的最大大小(例如,1 MB)但是用户可以选择50 MB文件并且可以上传它以发现PHP实际上不接受这种大小的文件 - 上传是完全没必要。

Can I prevent this somehow? 我能以某种方式阻止这种情况吗

(I can check file size in Javascript but not all browsers support this. Flash is an option but it's not universal either). (我可以在Javascript中查看文件大小,但并非所有浏览器都支持此。闪存是一种选择,但它也不是通用的)。

Thanks! 谢谢!

Use the LimitRequestBody Directive in .htaccess : .htaccess使用LimitRequestBody指令

Example (setting a 1Mb limit). 示例(设置1Mb限制)。 Create/modify your .htaccess file (in your webroot, or higher), and add: 创建/修改.htaccess文件(在您的webroot或更高版本中),并添加:

LimitRequestBody 1048576

When the limit is exceeded, the request will be interrupted . 超过限制时,请求将被中断 The user will get a response similar to: 用户将获得类似于以下内容的响应:

413 Request entity too large 413请求实体太大


Also: Rule 1: Never trust the client! 另外: 规则1:永远不要相信客户! You should always do such checks server-side, because the client can easily circumvent your JavaScript checks, and do anything which is not restricted by the server. 您应该始终在服务器端进行此类检查,因为客户端可以轻松绕过您的JavaScript检查,并执行不受服务器限制的任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM