PHP errors are ugly and should never be shown to your users. Luckily with PHP we can handle errors our own way using the set_error_handler function.
I’ll start by defining the error handling function which will write the error to a log file and stop execution.
function handleError($level, $error, $file, $line)
{
if ($logfile = fopen('log.txt', 'a'))
{
fwrite($logfile, date("F j, Y, g:i a") ." $error on line $line in $filen");
fclose($logfile);
}
die('An error has occured.');
}
Then set it as the error handling function.
set_error_handler('handleError');
Trigger an error to see if it works.
echo 100 / 0;
You could also get your function to notify you via email. Or you could forget about logging, and just display better looking errors…
function handleError($level, $error, $file, $line)
{
$errorhtml = '<div style="border: 4px solid #bfbfbf; font-size: 12px; font-family: arial, sans-serif; padding: 1px">';
$errorhtml .= '<div style="background-color: #a3503f; color: #ffffff; padding: 3px;">ERROR</strong></div>';
$errorhtml .= $error.'<br />';
$errorhtml .= 'Line: '.$line.'<br />';
$errorhtml .= 'File: '.$file;
$errorhtml .= '</div>';
echo $errorhtml;
}
