Custom PHP error handler function

Custom PHP error handler function

It rarely happens these days, but sometimes I create or work on vanilla PHP projects and sites. Without exceptions being thrown all over the place, debugging can be a major pain. This tiny snippet will help with that. I would recomment using this on production (and staging) sites rather than development site or your inbox may be filled with mails in no time. When using, omit the last line, it’s for testing by provoking an error.

<?php
set_error_handler('error_alert', E_ALL); // set to catch all possible errors
function error_alert($number, $string, $file, $line, $context)
{
    $err[] = 'Number: '.$number;
    $err[] = 'String: '.$string;
    $err[] = 'File: '.$file;
    $err[] = 'Line: '.$line;
    $err[] = 'Context: '.$context;
    // no output, just send mail
    mail('recipient@address', 'An error occured on your [prod/staging/dev] site http://domain.com', 'Error details:'.PHP_EOL.PHP_EOL.print_r($err, true), "From: sender@address");
}

// provoke error with non-existant variable for testing purposes
echo $hallo;

Leave a Reply

Your email address will not be published. Required fields are marked *

8 + 8 =