views:

91

answers:

2

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.

A: 

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!

Charles
I made it clear in my question I'm not trying to catch the errors using those PHP tricks, I just need to log them and handle them in some way. Using a PHP module seems the most likely way, but I can't find much information about the error handling in PHP modules.
PeterBelm
I also made it clear in my answer that you can't catch, but you can log. :)
Charles
+1  A: 

By default all errors are passed to web server error log but you can change it in php.ini by specifying path to your own file via error_log setting. So what is left to do is to write some separate script/app to parse / send data / truncate log file every day / whatever and run it as cron job.

dev-null-dweller
The only problem with this is that I wouldn't be able to issue a redirect. I think with a PHP module I would be able to achieve this.
PeterBelm