Can I catch exit() and die() messages?
Solution 1
As best as I can tell this is not really possible. Some of the solutions posted here may work but they require a lot of additional work or many dependencies. There is no way to easily and reliable trap the die() and exit() messages.
Solution 2
Yes you can, but you need ob_start, ob_get_contents, ob_end_clean and register_shutdown_function
function onDie(){
$message = ob_get_contents(); // Capture 'Doh'
ob_end_clean(); // Cleans output buffer
callWhateverYouWant();
}
register_shutdown_function('onDie');
//...
ob_start(); // You need this to turn on output buffering before using die/exit
@$dumbVar = 1000/0 or die('Doh'); // "@" prevent warning/error from php
//...
ob_end_clean(); // Remember clean your buffer before you need to use echo/print
Solution 3
According to the PHP manual, shutdown functions should still be notified when die() or exit() is called.
Shutdown functions and object destructors will always be executed even if exit() is called.
It doesn't seem to be possible to get the status sent in exit($status). Unless you can use output buffering to capture it, but I'm not sure how you'd know when to call ob_start()
.
Solution 4
Maybe override_function() could be interesting, if APD is available
Beau Simensen
Updated on June 20, 2022Comments
-
Beau Simensen almost 2 years
I'd like to be able to catch
die()
andexit()
messages. Is this possible? I'm hoping for something similar toset_error_handler
andset_exception_handler
. I've looked atregister_shutdown_function()
but it seems to contain no context for the offendingdie()
andexit()
calls.I realize that
die()
andexit()
are bad ways to handle errors. I am not looking to be told not to do this. :) I am creating a generic system and want to be able to gracefully logexit()
anddie()
if for some reason someone (not me) decides this is a good idea to do.