Can I catch exit() and die() messages?

16,231

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

Share:
16,231
Beau Simensen
Author by

Beau Simensen

Updated on June 20, 2022

Comments

  • Beau Simensen
    Beau Simensen almost 2 years

    I'd like to be able to catch die() and exit() messages. Is this possible? I'm hoping for something similar to set_error_handler and set_exception_handler. I've looked at register_shutdown_function() but it seems to contain no context for the offending die() and exit() calls.

    I realize that die() and exit() 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 log exit() and die() if for some reason someone (not me) decides this is a good idea to do.