Summary of the use of the seterrorhandler function in PHP

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, the system returns the null set_error_handler () function to set the custom error handler. 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.

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.

 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 (! 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 script exit when an Error occurs; break; case E_WARNING: echo" WARNING: [ID $ errno] $ errstr (Line: $ errline of $ errfile) n "; break; default: // do not display Notice-level error break ;}}

In this way, a custom error processing function is defined. how can we hand over error processing to this custom function?

// Apply it to the 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) {}// three methods are as follows: set_error_handler ('nonclassfunction '); // directly convert to a common function NonClassFunction set_error_handler (array ('callbackclass ', 'staticfunction'); // go to the static method StaticFunction $ o = & new Callback under the CallbackClass class Class (); set_error_handler (array ($ o, 'callbackfunction'); // The constructor to convert to a Class is essentially the same as the fourth one below .. $ O = new CallbackClass (); // The following may also prove usefulclass CallbackClass {function CallbackClass () {set_error_handler (array (& $ this, 'callbackfunction ')); // the & is important} function CallbackFunction () {// refers to $ this }}

The following is a brief introduction to the set_error_handler () function of PHP.

Definition and usage

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.

Syntax

Set_error_handler (error_function, error_types)

Parameter description

Error_function is required. Specifies the function to run when an error occurs.
Error_types is optional. Specifies at which error report level a user-defined error will be displayed. The default value is "E_ALL ".

Tips and comments

Tip: If this function is used, it will completely bypass the standard PHP error handler. if necessary, the user-defined error handler must terminate the (die () script.

Note: If an error occurs before the script is executed, the custom error handler will not be used because the custom program has not been registered at that time.

Example

 Custom error: [$errno] $errstr
"; echo " Error on line $errline in $errfile
"; echo "Ending Script"; die(); }//set error handlerset_error_handler("customError");$test=2;//trigger errorif ($test>1) { trigger_error("A custom error has been triggered"); }?>

Output:

Custom error: [1024] A custom error has been triggered
Error on line 19 in C:/webfolder/test. php
Ending Script

For more information about the usage of the set error handler function in PHP, refer to the PHP Chinese website!

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.