PHP large file upload results in empty $_FILES array

I was just working on a PHP file upload class, and found some inconsistent behavior in PHP. If you upload a file that is larger than the php.ini directive post_max_size, it will silently fail, and the $_FILES and $_POST arrays will be empty. It won't return an error code, it will just look like no file was uploaded.

This is quite annoying since almost every other file upload related error can by checked in the $_FILES['userfile']['error'] array. For example, if the file is larger than the upload_max_filesize directive, error will be set to 2, and you can report back to the user that the file is too large.

This error handling seems really inconsistent. Why have an error for one setting but not the other? Why not just create another error message in $_FILES['userfile']['error'] for post_max_size.

It looks like $_SERVER['CONTENT_LENGTH'] is set even if the upload is greater than post_max_size. So you could check if $_FILES is empty and $_SERVER['CONTENT_LENGTH'] is greater than the post_max_size, you could report back the file is too large to the user.

Update: I just realized I forgot to mention probably the most common reason file uploads don't work is because the HTML form doesn't have enctype="multipart/form-data" attribute. For every form that uploads files, this attribute must be on the <form> element or the browser will not send the file to the server.