views:

56

answers:

2

Afternoon,

I've been looking around for a while without success to see if there's a method to display a custom error page, whenever any PHP error arises, hiding the error from users - currently achieved by error_reporting(0), then emailing the specific error to my email address.

Initial logic (I know it's not right, it's just to help you understand better):

if(error_reporting){
    ob_clean();
    include('classes/email.php');
    $email = new email($pdo);
    $email->mailError(ERROR_REPORT);
    include('error-page.php');
    die();
}

Any help would be much appreciated, thanks!

+1  A: 

Well, you could use a custom error handling function. See set_error_handler()

function sendMailOnError($errno, $errstr, $errfile, $errline, $errcontext) {
    $subject = 'An Error Occured';
    $body = "An Error Occured\n\n".
            "$errstr [$errno]\n".
            "File: $errfile\n".
            "Line: $errline\n".
            "Current local variables: ".print_r($errcontext, true);
    //send the email here
} 

set_error_handler('sendMailOnError');
ircmaxell
I've noticed that function, but is there way to do this, then define a custom page to be displayed, instead of dying with a blank / half rendered screen or displaying the error to the user?
Stann0rz
Well, you can do whatever you want in the handler. You could dump the output buffer `while (ob_get_level()) ob_end_clean();`, and then render your error page...
ircmaxell
+1  A: 

You can define a custom error handler function, and have that show the error page, no problem.

The only difficulty with this is with errors that occur after some HTML has already been output. In most cases, you can nevertheless shove a full error page down the browser's throat, but that is horrible practice, as you would essentially output two HTML structures, one of them broken.

What I like to do in such cases is either just output a message, or output a position: fixed div that will overlay anything that has already been output.

Something like

function errorPage($errno, $errstr, $errfile, $errline, $errcontext) {

   // Perform some filtering here, you don't want to die on every notice 
   // or deprecated warning

   echo "<div style='position: fixed; left: 0px; top: 0px;  bottom: 0px;'>";
   // ... you get the drift... add some more styling here
   echo "Error message goes here</div>";
} 

set_error_handler('errorPage');

The way to show a complete, clean error page, uncluttered by any previous output, is making extensive use of output buffering, and flushing the content only if no error has occurred at the end of the page.

Pekka