Discovered today you can report to a user if the file(s) he/she is uploading is too large without having to wait for the file to finish uploading by checking $_FILES – the $_FILES array for each form input of type “file” has an element called “error” which returns an error code without actually uploading the file if the file is larger than than upload_max_filesize in php.ini or $_POST[“MAX_FILE_SIZE”]. It can do this because a “Content-length” http header is sent to the server first, and the file itself is then sent in the body of the http request.
Here’s a very simple example.
The form:
<form enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1048576" /> <input type="file" name="image" /> <input type="submit"> </form>
The php:
if ($_FILES["image"]["error"] == UPLOAD_ERR_FORM_SIZE) { echo "file too big!"; }
Note that you shouldn’t just use MAX_FILE_SIZE as I’ve done above, you also need to set upload_max_filesize appropriately in php.ini
August 29, 2008 at 6:13 pm
[…] on his blog Cormac has posted a quick little tutorial on making things a bit faster when rejecting file uploads in PHP that are just a bit too large. […]
October 7, 2008 at 10:59 pm
I’ve done this to the letter.
Don’t understand why it seems to be downloading the entire file before it returns with the error.
Thoughts?
The server is a Mac.
November 28, 2008 at 3:49 pm
Sorry Jeff, I don’t know 😦 Don’t know anything about Macs at all