Summary _php instance of Set error handler function usage in PHP

Source: Internet
Author: User
Tags php error
The Set_error_handler () function sets the user-defined error-handling function. This function is used to create the user's own error handling method during runtime. The function returns the old error handler and returns null if it fails.

Let's look at some examples below.

Set_error_handler ()

PHP provides the function Set_error_handler () of the custom error handling handle starting from 4.1.0, but very few script writers know. Set_error_handler This function is a good way to prevent false path leaks, of course, there are other more functions.

1. Can be used to mask errors. An error will leak some information to the user, most likely to become a hacker attack on your site tools. And let the user feel that your level is very lame.

2. You can write down the wrong information and find out the problems of some production environment in time.

3. Can do the corresponding processing, when the error can be displayed to jump to a pre-defined error page, to provide a better user experience.

4. As a debugging tool, some things must be debugged in the production environment, but do not want to affect the users in use.

5 .....

Set_error_handler is used as follows:

Copy the Code code as follows:
View Sourceprint?1 string Set_error_handler (callback Error_Handler [, int error_types])

We use error_reporting (); The error message you see includes three parts, an error message, an absolute address for the error file, and the number of rows that occurred incorrectly. There is actually another type of error. Array ([Type] = 1 [message] = = Call to undefined method Someclass::somemedthod () [File] =/home/zhangy/www/aaa a/stasdf.php [Line] = 67), the absolute path of the page should not be exposed to others, or to some people can be called machine, in order to stop this, many people will use, Ini_set ("Display_errors", 0); The error message is directly blocked out. This is inconvenient, if we want to see the information to do? Every time you look, do you want to change the code, or to change the configuration of Apache, re-start it?

PHP has a function set_error_handler can solve this problem

Use the following:

Mixed Set_error_handler (callback $error _handler [, int $error _types = E_all | E_strict])

PHP function register_shutdown_function can also solve this problem

Use the following:

int register_shutdown_function (String $func)

Personally feel that the error function is defined by itself, at least three points of benefit,

1, will not show the absolute path of the file, security

2, even if there is a real error message, we can deal with the error message, so that the user will not see fatal error such things. Better User Experience

3, the project on-line, sometimes, you still want to help users to solve the problem, this time inevitably to modify the code, but we have to let the error message out, and can not let users see, this time, with set_error_handler such a function is very cool.

The individual did a little test

<?php 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 are using custom error handling to filter out the actual path. Suppose there is a variable $admin, we are used to determine whether the visitor is an administrator (can make this judgment by IP or login user ID)

Admin is the administrator's identity, and true is administrator.
The custom error handler must have these 4 input variables $errno, $errstr, $errfile, $errline, otherwise invalid.

function My_error_handler ($errno, $errstr, $errfile, $errline) {   //If 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 "program has stopped running, please contact the administrator. ";     Exit script exit when error level errors are encountered     ;     break;     Case e_warning:     Echo ' WARNING: [ID $errno] $errstr (line: $errline of $errfile) n ";     break;     Default:     //Do not show error break at notice level     ;   }}

So you can customize an error handler, so how do you give the wrong handling to the custom function?

Apply to Class Set_error_handler (Array (& $this, "Apperror")); The practice of the example Set_error_handler ("My_error_handler");

So easy, this can be a good solution to the security and debugging convenience contradictions. And you can also take a little thought to make the error message more beautiful to match the style of the website.

In the above example, I turn off the error message, and use my own function to handle the error, the above page will be reported fatal error, the wrong information reported that we can use ErrorHandler to control and processing.

Well, to summarize, here are three ways to use 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 (' Nonclassfun Ction '); Go directly to a normal function nonclassfunction Set_error_handler (Array (' Callbackclass ', ' staticfunction ')); Go to the static method under the Callbackclass class Staticfunction $o =& new Callbackclass (); Set_error_handler (Array ($o, ' callbackfunction ')); Going to the constructor of 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}}

Now let's take a moment to introduce the PHP Set_error_handler () function separately.

Definition and usage

The Set_error_handler () function sets the user-defined error-handling function.

This function is used to create the user's own error handling method during runtime.

The function returns the old error handler and returns null if it fails.

Grammar

Set_error_handler (Error_function,error_types)

Parameter description

Error_function required. Specifies the function to run when an error occurs.
Error_types is optional. Specifies the error reporting level at which user-defined errors are displayed. The default is "E_all".

Hints and Notes

Tip: If you use this function, the standard PHP error handler is completely bypassed, and if necessary, the user-defined error handler must terminate (Die ()) script.

Note: If an error occurs before the script executes, the custom error handler is not used because the custom program is not registered at that time.

Example

<?php//error handler Functionfunction customerror ($errno, $errstr, $errfile, $errline) {  echo "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: [1024x768] A custom error has been triggered
Error on line c:/webfolder/test.php
Ending Script

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