Simple PHP error handling

Tagged: PHP, Programming Date: 28th, November 2008

Here is a very simple way of custom handling php errors.
To use code below, apart from including it in your functions file, you will need to call function display_debug(); at the end of every page (assuming you wish to display debug on every page).

Nifty feature is that you don’t have to worry about turning off debug on production version of your website. Simply populate $ips array with IP addresses you are using and debug will be displayed only to you.

To display mysql errors in this debug, use trigger_error function (example trigger_error($sql.’ ‘.mysql_error($link) ,’DB_ERROR’);)

$ips = array('127.0.0.1','88.99.109.119');
set_error_handler("ErrorHandler");

function ErrorHandler($errno, $errstr, $errfile, $errline)
{
	global $error_handler;

	if (preg_match("/DB_ERROR/iUs", $errno))
	{
		$error_handler[] = "DB_ERROR* $errstr\n" . "Fatal error on line $errline in $errfile";
	}

    switch ($errno) {
   	case E_ERROR:
    case E_USER_ERROR:
        $error_handler[] = "E_USER_ERROR $errstr on line $errline in $errfile. $errstr\n";
        break;

    case E_WARNING:
	case E_USER_WARNING:
        $error_handler[] = "E_USER_WARNING on line $errline in $errfile. $errstr\n";
        break;

    case E_NOTICE:
	case E_USER_NOTICE:
        $error_handler[] = "NOTICE on line $errline in $errfile. $errstr\n";
        break;

	case E_PARSE:
        $error_handler[] = "E_PARSE on line $errline in $errfile. $errstr\n";
        break;

	case E_STRICT:
        $error_handler[] = "E_STRICT on line $errline in $errfile. $errstr\n";
        break;

	case E_DEPRECATED:
        $error_handler[] = "E_STRICT on line $errline in $errfile. $errstr\n";
        break;

    default:
        $error_handler[] = "UNKNOWN on line $errline in $errfile. $errstr\n";
        break;
    }
    return true;
}

function display_debug()
{
	global $error_handler, $_GET, $_POST, $_SERVER, $_SESSION, $_COOKIE, $_REQUEST, $ips;

	if (!in_array($_SERVER['REMOTE_ADDR'], $ips))
	{
		return;
	}
	?>


$_GET

$_POST

$_REQUEST

$_COOKIE

$_SERVER

$_SESSION

}

Leave a Reply