Don't allow > 2mb images

烈酒焚心 提交于 2020-01-24 13:44:24

问题


HI! How do i check if the users are trying to upload bigger than 2mb files? I would like to deny that and put an error message to the user who is trying to do that.

I know it is something like this, but what shall i change the 50000 to to become 2mb?

if ($_FILES['imagefile']['size'] > 50000 )
{
die ("ERROR: Large File Size");
} 

回答1:


2 MB is 2097152 bytes.

Change the 50000 to 2097152 and you're set.




回答2:


The 5,000 is the number of byes, so basically you just need to convert 2MB to bytes. 1 MB is 1024 kilobytes, and 1024 bytes is 1 kilobyte. Doing the maths, we get:

2 megabytes = 2 097 152 bytes

Basically, you can calculate this in code form

$maxFileSize = $MB_limit * 1024 * 1024;

And check that the file size does not exceed $maxFileSize.




回答3:


Assuming that you have a file field in a form, called 'upload', you can check the size of the file as follows:

if ($_FILES['upload']['size'] > $max_upload_size) { echo "File too big"; }

Where $max_upload_size is the maximum size you want to allow (obviously you'll want to replace the echo statement with a more useful error message).

You can also use the upload_max_filesize setting in the php.ini file, but this will cause your users to see a PHP error if they exceed this limit, rather than your custom error message.



来源:https://stackoverflow.com/questions/1226855/dont-allow-2mb-images

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!