Limiting upload file size

Limiting upload file size
5 (100%) 1 vote

Limiting upload file size

We can configure upload max file size in php.ini file, but this is a global maximum for all of PHP.

If we want to configure max file size in a particular case, we can do that by adding an attribute to HTML form for MAX_FILE_SIZE.

<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size;"?>"/>

PHP will automatically detect that value when it’s submitted with a form and use it to limit the file size for that particular form.

That value MAX_FILE_SIZE needs to be expressed in bytes.

$max_file_size = 1048576;// 1MB

When a file is uploaded via a form and and we set MAX_FILE_SIZE value in form, the first thing that PHP will do, is to check which php.ini upload MAX_FILE_SIZE value is, to make sure that we haven’t gone over that global limit.

Then the second thing that PHP will do is to check if MAX_FILE_SIZE has been sent. And if it has, then it’s going to use that as a limit for this form.

But be careful, MAX_FILE_SIZE can be spoofed!
Someone can take the form and just modify or completely strip out our MAX_FILE_SIZE declaration and send us a spoofed form that no longer had that limit there. Fortunately we still have global php.ini limit set of upload MAX_FILE_SIZE.

In practice, is a good idea to have MAX_FILE_SIZE declared in our forms, but you shouldn’t rely on it.

To determine the size for a file, you can use the php file size function.

int filesize ( string $filename )[//php]
Gets the size for the given file, <strong>always in bytes</strong>!


$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename);

Leave a Reply

Your email address will not be published. Required fields are marked *