Backend Coder Logo

Avoiding 500 Internal Server Error Timeout in PHP

Published: 9th February 2015

I found that this error was due to an infinite/deeply-nested loop in my code. We may have a recursive function (one that calls itself) that takes too long to complete (usually > 30s) and the sever maximum execution time is hit.

clock tower

To get around this 500 Internal Server Error Timeout in PHP we can build into our recursive function a timer that triggers a break from the loop just short of the server timeout (in my testing 1s was too short, so I used a 5s margin).

The Code


class MyClass
{
  private $max_time;

  public $result;

  public function myFunc()
  {
    sleep (1);
    if (time() > $this->max_time)
      $this->result = "Timed out";
    else
      $this->myFunc();
    return $this->result;
  }

  function __construct() {
    $t = (int) ini_get('max_execution_time');
    if ($t < 25)
      $t = 30;

    $this->max_time = time() + $t - 5;
    $this->result = 'OK';
  }
}

$test = new MyClass();

echo $test->myFunc();

The output from this test script should be: Timed out

This kind of script is useful if it is not vital that the script fully completes it's operation, since an error 500 prevents the server from executing subsequent scripts in the pipeline.

Well, I was testing on my local host server where it did not seem to continue beyond the first 500 error. But I hoped that there would be some kind of parallel processing of the Ajax requests that would keep things moving along. But alas it was not the case in my test server (WAMP) environment.

You can extend the timeout via code, but I think it is a bad idea unless the code is running in the background and you have another mechanism to break out of the loop if things go wrong. And if you are on a shared hosting plan, it could get your account suspended if your script consumes excessive server resources.