Summary of usage of set_error_handler in php_PHP tutorial

WBOY
Release: 2016-07-12 09:08:04
Original
923 people have browsed it

Summary of usage of set_error_handler in php

The set_error_handler() function sets a user-defined error handling function. This function is used to create the user's own error handling method during runtime. This function returns the old error handler, or null on failure. Let’s look at some examples.


set_error_handler()

PHP has provided a custom error handling handle function set_error_handler() since 4.1.0, but few script writers know it. The set_error_handler function can prevent error paths from being leaked, and of course it has other functions.

1. Can be used to block errors. If an error occurs, some information will be exposed to users, and it is very likely to become a tool for hackers to attack your website. Second, it makes users feel that your level is very low.
2. You can write down error information and discover some problems in the production environment in a timely manner.
3. Corresponding processing can be done. When an error occurs, a jump to a predefined error page can be displayed to provide a better user experience.
4. It can be used as a debugging tool. Sometimes you have to debug something in the production environment, but you don’t want to affect the users who are using it.
5. . . .
The usage of set_error_handler is as follows:

view sourceprint?1 string set_error_handler ( callback error_handler [, int error_types])



The error message we see using error_reporting(); includes three parts, the error message, the absolute address of the error file, and the number of lines where the error occurred. In fact, there is another type of error. Array ( [type] => 1 [message] => Call to undefined method SomeClass::somemedthod() [file] => /home/zhangy/www/aaaa/stasdf.php [line] => 67 ), it is best not to expose the absolute path of the page to others, otherwise it will give some people an opportunity to complain. In order to prevent this, many people will use ini_set("display_errors",0); to directly block the error message. This is inconvenient. What if we want to read the information? Do I need to change the code every time I check it, or change the configuration of apache and restart it?

PHP has the function set_error_handler to solve this problem

Usage is as follows:

mixed set_error_handler ( callback $error_handler [, int $error_types = E_ALL | E_STRICT ] )

The php function register_shutdown_function can also solve this problem

Usage is as follows:

int register_shutdown_function ( string $func )

Personally, I feel that defining the error reporting function by yourself has at least three advantages,

1. The absolute path of the file will not be displayed, which is safer

2. Even if an error message does appear, we can process the error message so that users cannot see such things as fatal errors. Better user experience

3. After the project goes online, sometimes you still have to help users solve problems. At this time, it is inevitable to modify the code, but we also want the error message to be reported and not allowed to be seen by users. At this time, use set_error_handler like this The function is very cool.

I did a small test

error_reporting(0);

register_shutdown_function('error_alert');
function error_alert()
{
if(is_null($e = error_get_last()) === false)
{
set_error_handler('errorHandler');
if($e['type'] == 1){
trigger_error("fatal error", E_USER_ERROR);
}elseif($e['type'] == 8){
trigger_error("notice", E_USER_NOTICE);
}elseif($e['type'] == 2){
trigger_error("warning", E_USER_WARNING);
}else{
trigger_error("other", E_USER_OTHER);
}

}else{
echo "no error";
}
}

set_error_handler('errorHandler');

function errorHandler($errno, $errstr, $errfile, $errline,$errcontext)
{
switch ($errno) {
case E_USER_ERROR:
echo "My ERROR [$errno] $errstr
n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
n";
break;

case E_USER_WARNING:
echo "My WARNING [$errno] $errstr
n";
echo " warning on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
n";
break;

case E_USER_NOTICE:
echo "My NOTICE [$errno] $errstr
n";
echo " notice on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
n";
break;

default:
echo "Unknown error type: [$errno] $errstr
n";
echo " warning on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
n";
break;
}

return true;
}

class SomeClass {
public function someMethod() {

}
}

SomeClass::someMedthod();

$a="asdf";
foreach($a as $d){
echo $d;
}
?>

Now we use custom error handling to filter out the actual paths. Suppose there is a variable $admin, which we use to determine whether the visitor is an administrator (this determination can be made by IP or logged in user ID)

//Admin is the identity determination of the administrator, true is the administrator.
//The custom error handling function must have these four input variables $errno, $errstr, $errfile, $errline, otherwise it will be invalid.
function my_error_handler($errno,$errstr,$errfile,$errline)
{
//If you are not an administrator, filter the actual path
If(!admin)
{
          $errfile=str_replace(getcwd(),"",$errfile);
         $errstr=str_replace(getcwd(),"",$errstr);
}  
switch($errno)
{
case E_ERROR:
echo "ERROR: [ID $errno] $errstr (Line: $errline of $errfile) n";
echo "The program has stopped running, please contact the administrator.";
//Exit the script when encountering an Error level error
exit;
break;

case E_WARNING:
echo "WARNING: [ID $errno] $errstr (Line: $errline of $errfile) n";
break;

           default:
//Do not display Notice level errors
break;
}  
}

In this way, an error handling function is customized, so how to hand over error handling to this custom function?

// Apply to class
set_error_handler(array(&$this,"appError"));

//Example method
set_error_handler("my_error_handler");

So easy, in this way, the contradiction between security and debugging convenience can be well solved. And you can also put some thought into making the error message more beautiful to match the style of the website.



In the above example, I turned off the error message and used my own function to handle the error. The page above will report a fatal error. We can use errorHandler to control and handle the reported error message.

Okay, to summarize, here are three uses of set_error_handler:

Php code
class CallbackClass {
function CallbackFunction() {
// refers to $this
}

function StaticFunction() {
// doesn’t refer to $this
}
}

function NonClassFunction($errno, $errstr, $errfile, $errline) {
}

//The three methods are as follows:

1: set_error_handler(‘NonClassFunction’); // Go directly to a normal function NonClassFunction

2: set_error_handler(array(‘CallbackClass’, ‘StaticFunction’)); // Go to the static method StaticFunction
under the CallbackClass class
3: $o =& new CallbackClass();
set_error_handler(array($o, ‘CallbackFunction’)); // Go to the constructor of the class, which is essentially the same as the fourth item below.

4. $o = new CallbackClass();

// The following may also prove useful:

class CallbackClass {
function CallbackClass() {
set_error_handler(array(&$this, ‘CallbackFunction’)); // the & is important
}

function CallbackFunction() {
// refers to $this
}
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1058035.htmlTechArticleSummary of the usage of set_error_handler in php The set_error_handler() function sets a user-defined error handling function. This function is used to create user's own error handling methods during runtime...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template