2

I am wondering if I can hook a method in a include, that will email me the debug logs if any of my pages (that uses that include) crashed.

Is there a method that is executed after a fatal error?

Pentium10
  • 204,586
  • 122
  • 423
  • 502

2 Answers2

5

You can use register_shutdown_function() for this. You pass a function name as a parameter to this function, and that function is called when the application exits, for whatever reason.

You can use this time to catch and log any fatal errors, but you can't recover from them (they are fatal, after all). I think encounter a fatal error within this function, it's game over. There's no logging that.

In your shutdown function, you'll want to check if the shutdown was due to a fatal error and run logging code if it was:

function shutdown() {
  $lastError = error_get_last(); // returns an array with error information:
    switch($lastError['type']){
      case E_ERROR:
      case E_PARSE:
      case E_CORE_ERROR:
      case E_CORE_WARNING:
      case E_COMPILE_ERROR:
      case E_COMPILE_WARNING:
          // log the fatal error
          break;
    }
}
graywolf
  • 7,092
  • 7
  • 53
  • 77
AgentConundrum
  • 20,288
  • 6
  • 64
  • 99
  • Also similar and other examples listed here: http://stackoverflow.com/questions/277224/how-do-i-catch-a-php-fatal-error – Bill Ortell Feb 18 '13 at 16:35
1

You can catch all errors but fatal errors using set_error_handler(). Unfortunately even "harmless" things like calling undefined functions are fatal and cannot be handled.

However, you can enable error_log in php.ini and set it to log errors to syslog. You'll also get fatal errors in this log.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 2
    You can catch fatal errors using `register_shutdown_function()` as well. Also, you should know that there is also a `set_exception_handler()` which acts like `set_error_handler()` but for uncaught exceptions. – AgentConundrum Dec 10 '10 at 14:02
  • @Agent: How to determine why the script shut down? If you know that, please answer in [this question](http://stackoverflow.com/questions/4410632/handle-fatal-errors-in-php-using-register-shutdown-function). – ThiefMaster Dec 10 '10 at 15:55
  • @TheifMaster: I left an answer on *this* question, since I didn't see your comment until your question had already been answered. It's relevant here as well, after all. – AgentConundrum Dec 10 '10 at 21:35