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);
Hello there!I hope you find this post useful!
I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.
If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!