PHP, WEB

Modify error reporting behavior in PHP Part 2

In this article we will see how to handle errors with our own function.

PHP allows you to handle errors with the set_error_handler() function.

This function takes two arguments. The first argument is the name of our function to handle errors.
The second argument allows you to define which errors the function handles. ex. E_ALL, E_STRICT etc

Let’s see an example of a function which handles errors:

1
2
3
4
5
6
7
8
9
10
11
function myerrorhandler($err_no, $err_str, $err_file, $err_line, $err_context){
    $error  = '** PHP Error **rn';
    $error .= 'Number: '.$err_no.'rn';
    $error .= 'String: '.$err_str.'rn';
    $error .= 'File: '.$err_file.'rn';
    $error .= 'Line: '.$err_line.'rn';
    $error .= 'Context: '.print_r($err_context, TRUE).'rn';
    //echo or save to logs
    echo str_replace('rn', '<br>', $error);
    error_log($error, 3, 'path_to_logs');
}

for ex.

set_error_handler('myerrorhandler');

or

set_error_handler('myerrorhandler', E_STRICT);