Fast server-side rejection of large image uploads using $_FILES

August 28, 2008

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

About these ads

3 Responses to “Fast server-side rejection of large image uploads using $_FILES”


  1. [...] 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. [...]

  2. jeff Says:

    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.

  3. cormacscode Says:

    Sorry Jeff, I don’t know :( Don’t know anything about Macs at all


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: