tags:

views:

382

answers:

1

I'm working on a PHP form that attaches a file to an email, and trying to gracefully handle cases where the uploaded file is too large.

I've learned that there are two settings in php.ini that affect the maxiumum size of a file upload: upload_max_filesize and post_max_size.

If a file's size exceeds upload_max-filesize, PHP returns the file's size as 0. That's fine; I can check for that.

But if it exceeds post_max_size, my script fails silently and goes back to the blank form.

Is there any way to catch this error?

+5  A: 

From http://ca2.php.net/manual/en/ini.core.php#ini.post-max-size

If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. , and then checking if $_GET['processed'] is set.

So unfortunately, it doesn't look like PHP sends an error. And since it sends am empty $_POST array, that is why your script is going back to the blank form - it doesn't think it is a POST. (Quite a poor design decision IMHO)

This commenter also has an interesting idea.

It seems that a more elegant way is comparison between post_max_size and $_SERVER['CONTENT_LENGTH']. Please note that the latter includes not only size of uploaded file plus post data but also multipart sequences.

Matt McCormick
Not true; there is an error flag in the files array.
Pekka
Please read the bolded part. That is if the file size exceeds upload_max_filesize, the user is asking what happens when the form exceeds post_max_size. post_max_size should be set higher than upload_max_filesize to try to avoid this issue but the OP may have reasons for keeping it the same.
Matt McCormick
Sorry, I mixed up post_max_size and upload_max_filesize. +1
Pekka
deleted mine and upvoted here
Gordon
@Matt - post_max_size IS set higher than upload_max_filesize, but I still get the failure if the upload exceeds both. If it falls between the two, I see that the file size shows 0.
Nathan Long
Is post_max_size available to a PHP script for comparision purposes?
Nathan Long
You've solved it, but yes post_max_size is available. Just do ini_get('post_max_size'). ini_get() can also be used to check other INI settings.
Matt McCormick
@Matt - I will make a note of ini_get(). Thank you for your help. You rock.
Nathan Long
So far, it looks like $_SERVER['CONTENT_LENGTH'] is not available - if I exceed `max_post_size`, my script terminates. I can't even echo that value. Oh well.
Nathan Long