Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging fatal/parse errors in PHP5

I'm writing an error logging service that will be integrated into websites running on my server, that will email me error batches, etc.

So I've been trying to find out if there's a way to handle fatal and parse errors, however not using the tricks to handle it in PHP code (output buffer, shutdown function). I'm quite happy to write some C code or something to handle it outside of my PHP code. I would also like to issue a redirect if possible (my sites use output buffering so there shouldn't be any headers sent).

I'm pretty sure this could be done with a PHP module, but I've never written one and have no idea where to start.

like image 733
PeterBelm Avatar asked Oct 14 '22 06:10

PeterBelm


1 Answers

There is no way to catch a fatal or parse error in PHP. But..

In 5.2, they added error_get_last(). You can call it inside a shutdown function and perform logging. An untested 5.3 example for firing off a mail when there was a fatal error:

<?php
register_shutdown_function(function(){
    $err = error_get_last();
    if(is_array($err) && array_key_exists('type', $err) $err['type'] > 0 
      && ($err['type'] == E_ERROR || $err['type'] == E_PARSE) {
        error_log("Oh noes, a fatal: " . var_export($err, true), 1, '[email protected]');
    }
});

(You'll need to use a callback if you aren't on 5.3 and can't do anonymous functions.)

Unfortunately because this is handled in a shutdown function, chances are that headers have already been emitted and you might not be able to provide anything useful to the user. This depends on the rest of the application, though, so it might work out for you. Try it and find out!

like image 64
Charles Avatar answered Oct 27 '22 19:10

Charles