Category Archives: PHP

Detecting when an upload exceeds the post_max_size and/or the upload_max_filesize

The other day I was working through a problem where a client was having trouble uploading an image. After testing and ruling out a browser issue, I decided to see what happened if I tried uploading an image that was larger than the post_max_size and the upload_max_size. It loaded… and loaded… and loaded some more and finally the page loaded. It didn’t seem to do anything though. No errors or anything, the file just didn’t get uploaded. After some digging with no success, I got a tip from my¬†colleague Ryan Freebern¬† that PHP loses all of the POST data when the file size is above the limit. He also pointed me to a bit of code to help detect when this occurs so that I could fail more gracefully and present the user with a message letting them know why it did not work.

This is an abridged version of the code that I put together based on the code Ryan sent me as well as this article by Andrew Curioso about “Detecting file size overflow in PHP

$POST_MAX_SIZE = ini_get('post_max_size');
$mul = substr($POST_MAX_SIZE, -1);
$mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1)));
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > $mul*(int)substr($POST_MAX_SIZE, 0, strlen($POST_MAX_SIZE) - 1)) {
   return false;
} else {
   return true;
}

I also added in a little bit of client side validation using the FileReader API so that there was a first line of defense against a large file. Otherwise the large file still gets sent to the server before it knows it is too large.

// check if FileReader API is there and then check if the file size does not exceed the limit
if (typeof FileReader !== "undefined") {
// $(this) is a jQuery object of the file input
   if ($(this)[0].files[0].size > 8388608) {
      $('#message').html('Image is too large, must be under 8M').show();
      return false;
   }
}