Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gracefully handle files that exceed PHP's `post_max_size`?

Tags:

php

upload

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?

like image 280
Nathan Long Avatar asked Jan 25 '10 16:01

Nathan Long


People also ask

How do I increase my max upload size at runtime?

To increaes file upload size in PHP, you need to modify the upload_max_filesize and post_max_size variable's in your php. ini file. In addition, you can also set the maximum number of files allowed to be uploaded simultaneously, in a single request, using the max_file_uploads .

What is upload_max_filesize and Post_max_size?

upload_max_filesize is the maximum size of an uploaded file. This is the limit for a SINGLE file. post_max_size, on the other hand, is the limit of the entire body of the request (which may include multiple files as well as other stuff).


1 Answers

From the documentation :

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. <form action="edit.php?processed=1">, 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.

like image 69
Matt McCormick Avatar answered Sep 23 '22 01:09

Matt McCormick