Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

die

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.

like image 577
Beau Simensen Avatar asked Oct 01 '10 04:10

Beau Simensen


People also ask

Is die () and exit () functions in PHP do the exact same thing give an example?

The exit() method is only used to exit the process. The die() function is used to print the message. The exit() method exits the script or it may be used to print alternate messages. This method is from die() in Perl.

What are the differences between die () and exit () functions in PHP?

There is no difference between die and exit, they are the same. "This language construct is equivalent to die()." "This language construct is equivalent to exit()."

What does exit () do in PHP?

The exit() function prints a message and terminates the current script.

Which function can you use in error handling to stop the execution of a script and is equivalent to exit ()?

The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit() function only terminates the execution of the script.


2 Answers

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 
like image 54
MrQwerty Avatar answered Oct 12 '22 11:10

MrQwerty


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().

like image 41
Alex King Avatar answered Oct 12 '22 09:10

Alex King