How to catch the fatal error: Maximum execution time of 30 seconds exceeded in PHP
How about trying as PHP documentation (well... at least one of its readers) say:
<?php
function shutdown()
{
$a = error_get_last();
if ($a == null) {echo "No errors";}
else {print_r($a);}
}
register_shutdown_function('shutdown');
ini_set('max_execution_time', 1);
sleep(3);
?>
Have a look at the following links:
- http://www.php.net/manual/en/function.set-error-handler.php#106061
- http://www.php.net/manual/en/function.register-shutdown-function.php
Your only options are to increase the allowed execution time (setting it to 0 makes it infinite, but that is not recommended) of the script or spawn a new thread and hope for the best.
The reason that this isn't catchable is that it isn't really thrown. No one line of the code actually triggered the error, rather PHP said, "Nope, sorry, this is too long. Time to shut down now." And that makes sense. Imagine having a script with a max execution time of 30 seconds catching that error and taking another 30 seconds... in a poorly designed program, that opens up some rather nasty opportunities to exploit. At a minimum, it will create opportunities for DOS attacks.
This isn't an exception, it's an error. There are important differences between exceptions and errors, first and foremost errors can't be caught with try/catch semantics.
PHP scripts are built around a paradigm of short execution times, so PHP is configured by default to assume that if a script has been running for longer than 30 seconds it must be caught in an infinite loop and therefore should be terminated. This is to prevent an errant PHP script causing a denial of service, either by accident or by malicious intent.
However, scripts do sometimes need more running time than they are allocated by default.
You can try changing the maximum execution time, either by using set_time_limit()
or by altering the value of max_execution_time
in the php.ini
file to raise the limit. you can also remove the limit entirely by setting the execution time to 0, though this isn't recommended.
set_time_limit()
may be disabled by mechanisms such as disable_functions
so it might not be available to you, likewise you might not have access to php.ini
. If both of these are the case then you should contact your host for help.
One exception is PHP scripts run from the command line. Under these running conditions, PHP scripts may be interactive and need to spend a long time processing data or waiting for input. For this reason there isn't a max_execution_time
limit on scripts run from the command line by default.
EDIT TO ADD: PHP 7's error handling had a major overhaul. I believe that errors and exceptions are now both subclasses of Throwable. This may make the above no longer relevant for PHP7+, though I'll have to look more closely into the specifics of how error handling works now to be sure.