Summary of set_error_handler usage in php-PHP source code

Source: Internet
Author: User
The set_error_handler () function sets the custom error handling function. This function is used to create your own error handling methods during runtime. This function returns the old error handler. If it fails, null is returned. Here are some examples. The set_error_handler () function sets the custom error handling function. This function is used to create your own error handling methods during runtime. This function returns the old error handler. If it fails, null is returned. Here are some examples.

Script ec (2); script


Set_error_handler ()

PHP has provided the set_error_handler () function for customizing error handling handles since 4.1.0, but few script writers know it. The set_error_handler function can effectively prevent the leakage of error paths. Of course, there are other functions.

1. It can be used to block errors. When an error occurs, it will expose some information to the user, which is very likely to be a tool for hackers to attack your website. Second, let the user think that your level is very poor.
2. You can write down the error information and promptly discover problems in the production environment.
3. You can handle the error accordingly. When an error occurs, the page jumps to the pre-defined error page to provide a better user experience.
4. It can be used as a debugging tool. In some cases, you must debug some things in the production environment, but you do not want to affect the users in use.
5 .....
Set_error_handler is used as follows:

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

We use error_reporting (); to view the error information, which consists of three parts: Error information, absolute address of the error file, and number of lines in the error. In fact, there is another error type. 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, or give some people a title. To prevent this, many people will use it, ini_set ("display_errors", 0); the error message is blocked directly. This is inconvenient. What should we do if we want to view the information? Do I have to change the code or apache configuration every time I check it?

Php has the set_error_handler function to solve this problem.

The 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.

The usage is as follows:

Int register_shutdown_function (string $ func)

I personally think that the error function is defined by myself. There are at least three advantages,

1. the absolute path of the file is not displayed, which is more secure.

2. Even if an error message occurs, we can process the error message so that the user cannot see the fatal error. Good User Experience

3. After the project is launched, sometimes you still need to help users solve the problem. At this time, it is inevitable to modify the code, but we need to make the error message reported, so that users cannot see it, at this time, functions such as set_error_handler are very nice.

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 can use custom error handling to filter out the actual path. Assume that there is a variable $ admin, which is used to determine whether the visitor is an administrator (you can use the IP address or user ID to determine whether the visitor is an administrator)

// Identify admin as the administrator. true is the administrator.
// The custom error handler must have these four input variables $ errno, $ errstr, $ errfile, and $ errline. Otherwise, the error handler is invalid.
Function my_error_handler ($ errno, $ errstr, $ errfile, $ errline)
{
// Filter the actual path if it is not an administrator
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. Contact the administrator. ";
// Exit the script when an Error occurs.
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, a custom error processing function is defined. How can we hand over error processing to this custom function?

// Apply to Class
Set_error_handler (array (& $ this, "appError "));

// Example
Set_error_handler ("my_error_handler ");


So easy, which can solve the conflict between security and debugging convenience. In addition, you can also make some effort to make the error prompt more beautiful to match the website style.

In the above example, I turn off the error message and use my function to handle the error. The above page will report a fatal error, we can use errorHandler to control and handle the reported error messages.

Now, let's sum up the following three usage methods: 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 '); // directly convert it 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'); // The constructor to convert to the class is essentially the same as the fourth article 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
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.