Handling Fatal Error: Maximum Execution Time Exceeded in PHP
In the realm of PHP development, one can stumble upon the dreaded "Fatal error: Maximum execution time of 30 seconds exceeded." This error emerges when a script exceeds the time limit set by the server, typically 30 seconds by default.
While increasing the time limit may seem like a straightforward solution, it's not always practical. Moreover, capturing this error through an exception is not possible due to its fatal nature. However, there is an alternative approach to intercept it gracefully.
PHP's error_get_last() function allows you to retrieve the last error that occurred. Combining this with register_shutdown_function(), you can set up a callback to handle errors upon program termination. Here's an example:
<code class="php">function shutdown() { $error = error_get_last(); if ($error === null) { echo "No errors"; } else { print_r($error); } } register_shutdown_function('shutdown'); ini_set('max_execution_time', 1); // Setting a low time limit for demonstration purposes sleep(3);</code>
By calling register_shutdown_function('shutdown'), the shutdown() function will be executed after the script's execution or termination. In this handler, error_get_last() retrieves the latest error and prints it, providing you with the ability to log or handle the issue appropriately.
For more information and alternatives, refer to the following resources:
The above is the detailed content of How to Gracefully Handle the \'Maximum Execution Time Exceeded\' Fatal Error in PHP?. For more information, please follow other related articles on the PHP Chinese website!