views:

462

answers:

3

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");
}
A: 

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.

Rob Knight
Yes i know that, but what to write in the max_upload_size variabel? To fit my suggestions? 2mb? Howto ;)
2 MB = 2048 kilobytes. 2048KB = 2097152 bytes. (Apparently.)
Lucas Jones
+1  A: 

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.

Extrakun
+3  A: 

2 MB is 2097152 bytes.

Change the 50000 to 2097152 and you're set.

FWH
Thank u! That was needed!