File Upload from HTML form: client and server validation for maximum size

File uploading normally requires client validation (mainly as a UI improvement) and server validation (in case the client validation is bypassed/hacked).

The code

<input type="hidden" name="MAX_FILE_SIZE" 
 value="2621440"/>

only imposes a soft limit (in bytes) on the server side, therefore not a good practice since it can be altered by the user. The solution I adopted is composed by a server side validation AND a client validation (in JavaScript, mainly for a better user experience since it can be easily hacked as all the other JS solutions)

Client validation (JavaScript)

The idea is accessing the files JS property of the input field and read the file size on the ‘change’ event (when a file is selected by the user). If the selected files exceed¬†the max size, I simply display a clear user warning and disable the submit button. I’ve created a generic script that automatically listens to the change event for any file upload element, and reads the max upload size in bytes from the MAX_FILE_SIZE HTML input hidden element in the same form.

Server side validation (PHP)

Just set the desired value for ‘upload_max_filesize’ and ‘post_max_size’ PHP settings (php.ini). Alternatively, if you need application specific settings and you use apache as web server, add the following lines into the .htaccess in your web root

php_value upload_max_filesize 25M
php_value post_max_size 25M