Author: I.Roiban (3 Feb 05 11:06am)
Well, it is actually good to catch any error, so set the E_ALL and redirect its output to a log file or your own e-mail address like in this example:
# -------------------------------------------
define('WEBMASTER_EMAIL, 'webmaster@yourdomain.com');
define('PHP_ERROR_FILE', php_error_log.txt');
# -------------------------------------------
if (defined('PHP_ERROR_FILE')){
ini_set('error_reporting', E_ALL);
ini_set('ignore_repeated_errors', 0);
ini_set('html_errors', 0);
function e($type,$msg,$file,$line){ # custom error handler
/* this error handler is set to catch all errors and
log error, script, line, browser etc.
it also emails system administrator
*/
switch ($type) {
case 1: # E_ERROR: Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.
log_php_error($type,$msg,$file,$line);
exit;
break;
default:
log_php_error($type,$msg,$file,$line);
break;
}
}
set_error_handler("e"); # define a custom handler
}
function log_php_error($type,$msg,$file,$line){ # custom error handler
# stop logging or sending errors if more than 10 in the past 1 minute were logged
$ok=false;
if($fp = @fopen(PHP_ERROR_FILE, "r+")){
$last_access=fread($fp,10);
$logs_ratio=fread($fp,10);
if($last_access < (time() - 60)) {$logs_ratio = 0;} # reset the ratio to zero anyways if more than 1 minute since last error log was writen/emailed
# write to the beginning of the file in order to have the last time at the top for reading faster with fread above
if($logs_ratio < 10) {$ok = true;} # 10 per minute allowed
$logs_ratio = $logs_ratio + 1;
rewind($fp);
flock($fp,LOCK_EX);
fputs($fp,time() . sprintf("%-10s", $logs_ratio) . "\n"); # write time (10 chars) and ratio (10 chars) fixed lenght to avoid shortening of the next line
flock($fp,LOCK_UN);
fclose($fp);
}
if($ok){ # if less than 10 errors logged in in the past 1 minute proceed further
$e = time() . '|' . $type . '|' . $msg . '|' . $file . '|' . $line . '|' . $_SERVER['REQUEST_URI'] . '|' . $_SERVER['REMOTE_ADDR'] . '|' . $_SERVER['HTTP_USER_AGENT'];
# write to the end of the file
if($fp = @fopen(PHP_ERROR_FILE, "a")){
flock($fp,LOCK_EX); # acquire exclusive lock (writer)
fputs($fp,$e . "\n");
flock($fp,LOCK_UN); # release lock
fclose($fp);
}
if (defined('WEBMASTER_EMAIL')){
$error_array = explode('|',$e);
$error_array[0] = date("F j, Y, g:i a",$error_array[0]);
# e-mail error log to webmaster
$body = "<pre>+" . sprintf("%'--78s", '-') . "+\n";
$body .= '|' . sprintf("%-78s", ' P H P E R R O R R E P O R T') . "|\n";
$body .= '|' . sprintf("%'--78s", '-') . "|\n";
foreach($error_array as $value){
$body .= '| ' . sprintf("%-77s", $value) . "|\n";
}
$body .= '+' . sprintf("%'--78s", '-') . "+</pre>\n";
# To send HTML mail, set the Content-type header.
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-Type: text/html";
# and now mail its info
mail(WEBMASTER_EMAIL,'php error',$body,$header);
}
}
}
|