Scriptplayground

 Print Page | Close Window

Custom Error Handler

How to create a custom error handler in PHP

Have you ever wanted to create a custom error handler in PHP to replace the standard output to the browser? Well this is how you do it.

First you set up the error handler to replace the normal one, and set the ini values.

// Change defaults
ini_set('display_errors', 'Off');
ini_set('log_errors', 'On');
define('ERROR_LOG_PATH', 'error_log.txt'); // The path to the error log file

// set to the user defined error handler
set_error_handler("custom_err_handler");

Now that the custom function is defined we must then create it.

The function takes 4 arguments.

function custom_err_handler($num, $str, $file, $line) {
    print "Error Handler Called!";
    $err = "";
    $err .= "---- PHP Error ----\n";
    $err .= "Number: [" . $num . "]\n";
    $err .= "String: [" . $str . "]\n";
    $err .= "File: [" . $file . "]\n";
    $err .= "Line: [" . $line . "]\n\n";
    error_log($err, 3, ERROR_LOG_PATH);
}

Now to save an error you use "trigger_error" such as in the example.

Here is the complete code.

// set the error reporting level for this script
error_reporting(E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);

// Change defaults
ini_set('display_errors', 'Off');
ini_set('log_errors', 'On');

// set to the user defined error handler
set_error_handler("custom_err_handler");

// The path to the error log file
define('ERROR_LOG_PATH', 'error_log.txt');

// Our custom error handler function
function custom_err_handler($num, $str, $file, $line) {
	print "Error Handler Called!";
    global $error_log_path;
    $err = "";
    $err .= "---- PHP Error ----\n";
    $err .= "Number: [" . $num . "]\n";
    $err .= "String: [" . $str . "]\n";
    $err .= "File: [" . $file . "]\n";
    $err .= "Line: [" . $line . "]\n\n";
    error_log($err, 3, ERROR_LOG_PATH);
}

// function to test the error handling
function myFunction() {
	trigger_error("Just a sample errror message");
}

// Call our test function
myFunction();

Here is a snippet from the error file our function writes to

........
---- PHP Error ----
Number: [1024]
String: [Just a sample errror message]
File: [/path/to/file/cause_errors.php]
Line: [20]
........

That is all it takes to set up a custom error handler function.

If you have any questions don't hesitate to ask.


Find this article at:
http://scriptplayground.com/tutorials/php/Custom-Error-Handler/