Whenever you allow the public to upload files to your site, you’re opening a Pandora’s Box of potential issues.
What if they upload a file format you don’t want on your server?
What if they upload a file with an incorrect extension?
What if they upload a file that’s too large for your system to handle?
As it turns out, the third issue is relatively straight-forward to fix.
Before the fix
Let’s say your upload form initially consists of three parts:
- The form itself, correctly set up with
enctype="multipart/form-data"and pointing its action at your server - A file input field
- A hidden “action” input field to enable server-side filtering
When the file gets to the server, your code checks for the presence of the action flag and changes its logic (i.e. begins processing the form), and moves merrily along.
Unfortunately, if the file uploaded is larger than your server can handle, madness will ensue instead. The action flag won’t be hit and either the page acts as if nothing’s been submitted or, worse, your customer is left with a white-page-of-death.
Not sure which of the two doom-and-gloom eventualities plague your site? Check your server’s php.ini file for the post_max_size definition, then try submitting a file larger than that value. It will fail in a ball of fiery glory.
After the fix
When a PHP request exceeds the post_max_size setting, the server will automatically empty the contents of both $_POST and $_FILE. So if you’re keying application logic based on flags set in $_POST variables, it will fail miserably.
The fix is relatively simple.
Add whatever flags you’ll need in the $_POST object as query arguments on your form’s action attribute. This will submit them as both POST (assuming they’re still in hidden input fields) and GET parameters.
Now switch your application logic to check for $_REQUEST flags, and it will appropriately check the GET parameters, see the flags, and continue along.
Further, you can check if both the action flag is set and the $_POST array is empty to determine if you’re experiencing an error condition and alert your site visitors. It makes for a much more robust user experience, and prevents anyone from claiming your site is broken because they tried to upload something larger than you expected.
