Is there a way in PHP to trap the fatal error when the max execution time is reached and give the user a better message?
After reading the first two answers here, I had to test register_shutdown_function()
myself -- I didn't think it'd run. After all, how can a user function run once there's no more memory, or execution time has elapsed? I was surprised to learn that shutdown functions do run, even in an OOM situation, or when execution time has been exceded. Proof of concept:
To test memory limit:
<?php
function asdf() { echo "omg\n"; }
register_shutdown_function('asdf');
ini_set('memory_limit', '1000');
$x = '';
while(true) {
$x .= 'lkajsdlfkjasldkfjlaskdfjasldkfj';
}
Output:
PHP Fatal error: Allowed memory size of 262144 bytes exhausted (tried to allocate 169540 bytes) in /home/scratch.php on line 9
PHP Stack trace:
PHP 1. {main}() /home/scratch.php:0
Fatal error: Allowed memory size of 262144 bytes exhausted (tried to allocate 169540 bytes) in /home/scratch.php on line 9
Call Stack:
0.0002 81360 1. {main}() /home/scratch.php:0
omg
To test execution time:
cat scratch.php
<?php
function asdf() { echo "omg\n"; }
register_shutdown_function('asdf');
set_time_limit(1);
while(true) {}
Output:
PHP Fatal error: Maximum execution time of 1 second exceeded in /home/scratch.php on line 7
PHP Stack trace:
PHP 1. {main}() /home/scratch.php:0
Fatal error: Maximum execution time of 1 second exceeded in /home/scratch.php on line 7
Call Stack:
0.0002 80200 1. {main}() /home/scratch.php:0
omg
Note that, to get your message to display before PHP's error output, you'd have to disable PHP's error output entirely. Which is best practice for a production site anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With