Relationship between php’s memory_limit, upload_max_filesize and post_max_filesize Relationship between php’s memory_limit, upload_max_filesize and post_max_filesize apache apache

Relationship between php’s memory_limit, upload_max_filesize and post_max_filesize


PHP will accept uploaded files that are individually smaller than upload_max_filesize and together take less than post_max_size bytes. The PHP documentation is wrong with regard to memory_limit which does not need to hold the file contents posted.

The following configuration works with both Apache2 module and CGI, and accepts files smaller than 1G.

 upload_max_filesize = 1G post_max_size = 1G memory_limit = 32M


Do I need to be concerned about setting post_max_filesize >> memory_limit?

Only if you plan on reading an entire file into memory and the file that you read in is larger than the space you have allocated to PHP (i.e. memory_limit), in which case you'll run out of memory.


My own personal experience is that you HAVE to have a memory_limit higher than post_max_size and upload_max_size.

The post_max_size refers to the entirety of the POSTed data. This includes any form fields that may have been included with the file itself. The upload_max_size is the largest allowable size a file can be within that upload.

For instance. with a post_max_size of 10mb and a upload_max_size of 1mb, you could upload 9 files, each 1mb in size, Why 9 files? because part of the POST data is the file metadata - filename, mimetype, file size, etc... This all takes up some space, so your 9 files will actually take up 9.01megabytes or so. The 0.99 leftover is too small for another file, so you can't upload that 10th, even though it fits within the upload_max_size limit.

As for memory_limit, not only do you have to have enough "room" for the files that were uploaded, you have to remember that this limit applies to the script as a whole. A memory_limit of 10mb would allow for only a 9megabyte file to be uploaded, because PHP itself and all the associated code and libraries will suck up (say) 1 megabyte already.

Even though the files aren't held in memory - they get dumped out to temp files as soon as possible, they are passed in to PHP from Apache via STDIN. PHP has to read the files from that stream and copy them out to the temporary files you use in the ['tmp_name'] section of the $_FILES array.

For whatever reason, PHP seems to be basically doing "file_get_contents()" and slurping the files up in bulk, rather than doing a streaming-type copy. Hence requiring a memory_limit that exceeds the largest allowed file size.