PHP Solution For Persistent Timeout Error

PHP Solution For Persistent Timeout Error

Perhaps you came across a message such as “Maximum execution time of 180 seconds exceeded” and went googling for a solution. The solution would probably be one of the following

By editing .htaccess

php_value max_execution_time -1

By editing php.ini 

max_execution_time=-1

By editing your PHP code

set_time_limit(-1); 
// OR
ini_set ('max_execution_time', -1);

But even after trying all these.. you are still getting the same error.

Here’s some possible reasons and solutions why.

    1. Your script is getting timed-out by Apache/LiteSpeed/Other Similar Web Server TechnologyIn your httpd.conf (in server config or vhost config), edit the TimeOut variable. The default should be 300.
      TimeOut 600
      
    2. Your using PHP-FastCGI or PHP-FPMThe error you are seeing is from apache’s fastcgi proxy who killed connection to php-fpm pool because your script did not outputted anything for 30 seconds.You can change idle-timeout in your apache config to extend it (cannot be 0):
      FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi -socket /run/php/php7.0-fpm.sock -idle-timeout 1800 -pass-header Authorization
    3. Apache or PHP isn’t resetting the execution time counter for unknown reasons
      Finally, if you still are not able to get it to work, simply try putting the code

      set_time_limit(-1)

      around different parts of your script/code. This is because each time you call set_time_limit it resets the timer / counter for the script. An example as shown below – I faced a problem with hashing large files and had to consistently make calls to set_time_limit

      $bytesToRead = 1024;
      $fp = fopen($filepath, "r");
      $ctx = hash_init('sha256');
      while (!feof($fp)) {
          hash_update($ctx, fgets($fp,$bytesToRead));
          set_time_limit(-1);  
      }
      $sha256 = hash_final($ctx);  
      fclose($fp);

Conclusion

Hopefully what I’ve shared will be useful for you in solving your issues. Should you need any help, feel free to let me know in the comments below.

Enjoyed the content ? Share it with your friends !

Leave a Reply

Your email address will not be published. Required fields are marked *