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

Viewed 41680

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?

6 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.

I had the same problem, and combined some of the solutions already posted here on this page (by @Doblas, @Lance Cleveland and @AbdullahAJM).

Additionally, my solution tries to sends a 413 Payload Too Large error (instead of 200 OK), which is of course only possible, when php.ini is not configured to display warnings.

// Check for Warning: php catch Warning: Unknown: POST Content-Length of bytes exceeds the limit of bytes in Unknown on line 0
// Sending 413 only works, if Warnings are turned off in php.ini!!!

// grab the size limits...
$postMaxSize = trim(ini_get('post_max_size')); 
if (strlen($postMaxSize)>0) {
   $postMaxSizeValue = substr($postMaxSize, 0, -1);
   $postMaxSizeUnit = strtolower(substr($postMaxSize, -1));
   $postMaxSize = 0; // make it fail save
   if (false !== filter_var($postMaxSizeValue, FILTER_VALIDATE_INT, array('options' => array( 'min_range' => 0)))) {
      switch ($postMaxSizeUnit) {
         case 'g': $postMaxSizeValue*=1024; // ... and fall through
         case 'm': $postMaxSizeValue*=1024; // ... and fall through
         case 'k': $postMaxSizeValue*=1024; break;
         default: if ($postMaxSizeUnit>='0' && $postMaxSizeUnit<='9') {
                     $postMaxSizeValue = (int) $postMaxSizeValue.$postMaxSizeUnit;
                  } else {
                     $postMaxSizeValue = 0;
                  }
      }
      $postMaxSize = $postMaxSizeValue;
   }
} else {
   $postMaxSize = 0;
}

if (empty($_FILES) && empty($_POST) &&
    isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST' &&
    isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $postMaxSize) {
    // if is a post request and $_POST variable is empty(a symptom of "post max size error")
    
    if (headers_sent()) {
       // echo out error and solutions...
       echo "<p style=\"color: #F00;\">\nPlease note that an error <b>413 Payload Too Large</b> should be sent, but the warning can't be catched, and so the client gets a <b>200 OK</b>. ".
            "Please turn off warnings in php.ini in order to achieve the correct behaviour.</p>"; 
    } else {
       http_response_code(413);
    }

    // catch file overload error: echo out error and solutions...
    echo "<p style=\"color: #F00;\">\nPlease note files larger than ".$postMaxSize." will result in this error!<br>".
         "Please be advised this is not a limitation in the script, this is a limitation of the hosting server.</p>";
    exit(1);
}
Related