How to Include Server Request URI in PHP Error Log

Having an error log in PHP is great because it allows you to see errors without showing them to your users. But, it’s often very difficult to fix errors without knowing what page a user was viewing that generated the error. Here’s some code that you can add to your PHP website to include the server request URI in your error log.

[cc lang=”php”]/* *************************/
/* HANDLE NON-FATAL ERRORS */
/* *************************/
function debugErrorHandler($errno, $errstr, $errfile, $errline)
{
if (error_reporting()!==0) {
switch ($errno) {
default:
error_log(“PHP Warning Debug: Server Request URI: ” . print_r($_SERVER[“REQUEST_URI”], true));
break;
}

return false; // false -> Execute PHP internal error handler
}
}

set_error_handler(‘debugErrorHandler’);

/* *************************/
/* HANDLE FATAL ERRORS */
/* *************************/
function shutDownFunction() {
# Using error_get_last is the “right” way, but it requires PHP 5.2+. The back-up is a hack.
if (function_exists(‘error_get_last’)) {
$lastPHPError = error_get_last();
$phpFatalError = isset($lastPHPError) && $lastPHPError[‘type’] === E_ERROR;
} else {
$phpFatalError = strstr($output, ‘<b>Fatal error</b>:’) && ! strstr($output, ‘</html>’);
}

if ($phpFatalError)
error_log(“PHP FATAL Debug: Server Request URI: ” . print_r($_SERVER[“REQUEST_URI”], true));
}

register_shutdown_function(‘shutDownFunction’);[/cc]

Add this to the top of your PHP pages (by including it) and you’ll see the server request URI in your error logs.