How to catch the fatal error: Maximum execution time of 30 seconds exceeded in PHP

Viewed 83290

I've been playing around with a system I'm developing and managed to get it to cause this:

Fatal error: Maximum execution time of 30 seconds exceeded

It happened when I was doing something unrealistic, but nevertheless it could happen with a user.

Does anyone know if there is a way to catch this exception? I've read around but everyone seems to suggest upping the time allowed.

8 Answers

I faced a similar problem and here was how I solved it:

<?php
function shutdown() {
    if (!is_null($error = error_get_last())) {
        if (strpos($error['message'], 'Maximum execution time') === false) {
            echo 'Other error: ' . print_r($error, true);
        } else {
            echo "Timeout!\n";
        }
    }
}

ini_set('display_errors', 0);
register_shutdown_function('shutdown');
set_time_limit(1);

echo "Starting...\n";
$i = 0;
while (++$i < 100000001) {
    if ($i % 100000 == 0) {
        echo ($i / 100000), "\n";
    }
}
echo "done.\n";
?>

This script, as is, is going to print Timeout! at the end.

You can modify the line $i = 0; to $i = 1 / 0; and it is going to print:

Other error: Array
(
    [type] => 2
    [message] => Division by zero
    [file] => /home/user/test.php
    [line] => 17
)

References:

Related