PHP Set_error_handler () function use "reprint"

Source: Internet
Author: User

When we write a program, there will inevitably be problems (often problems), and when PHP encounters an error, it gives the location of the error script, the number of rows, and the reason. A lot of people say it's not a big deal. Indeed, during the debugger phase, this is really nothing, and I think it is necessary to give the wrong path.

But the consequences of revealing the actual path are disastrous, and for some intruders, this information is very important, and in fact there are a lot of servers that are having this problem. Some network management simply set the PHP configuration file display_errors to off to solve (it seems that we are doing this), but I think this method is too negative.

Sometimes, we really need PHP to return the wrong information for debugging. And in the case of errors may also need to give the user a confession, or even navigate to another page.

So, what's the solution?

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:

String Set_error_handler (callback Error_Handler [, int error_types])

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.  //Custom error handling function must have these 4 input variables $errno, $errstr, $errfile, $errline, otherwise invalid.  function My_error_handler ($errno, $errstr, $errfile, $errline)  {      //If it is not an administrator to 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.

The original author gave two points to pay attention to the place, I also let out, hope to arouse the attention of our compatriots:

    1. E_error, E_parse, E_core_error, e_core_warning, E_compile_error, and e_compile_warning are not handled by this handle, which means they are displayed in the most primitive way. However, these errors are either compiled or the PHP kernel is faulty and will not normally occur.
    2. After using Set_error_handler (), the error_reporting () will be invalidated. That is, all errors (except for the above errors) will be given to the custom function processing.

Finally, the original author gives an example (what a really serious and responsible good Man ha.) )

Define a function, define it in other files, and call function MyErrorHandler ($errno, $errstr, $errfile, $errline) with require () {//For security reasons, do not expose the true      Real physical path, the following two lines filter the actual path $errfile =str_replace (GETCWD (), "", $errfile);        $errstr =str_replace (GETCWD (), "", $errstr);          Switch ($errno) {case E_user_error:echo "<b>my error</b> [$errno] $errstr <br/>\n";          echo "Fatal error on line $errline in file $errfile"; echo ", PHP". Php_version. " (" . Php_os.          ") <br/>\n";          echo "Aborting...<br/>\n";          Exit (1);        Break          Case E_user_warning:echo "<b>my warning</b> [$errno] $errstr <br/>\n";        Break          Case E_user_notice:echo "<b>my notice</b> [$errno] $errstr <br/>\n";        Break          Default:echo "Unknown error type: [$errno] $errstr <br/>\n";      Break  }/* Don ' t execute PHP Internal Error handler */return TRUE;  }  The following begins the connection to the MySQL server, we deliberately specify the MySQL port is 3333, the actual is 3306.  [Email protected]_pconnect ("localhost:3333", "root", "password");  Set_error_handler (MyErrorHandler);  if (! $link _id) {trigger_error ("error", E_user_error);   }

Well, to summarize, here are three ways to use Set_error_handler:

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:    1:set_error_handler (' Nonclassfunction ');  Go directly to a normal function nonclassfunction    2:set_error_handler (Array (' Callbackclass ', ' staticfunction '));//Go to static method under Callbackclass class Staticfunction    3: $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.    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     }  }  

Use of the PHP Set_error_handler () function "reproduced"

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.