Set in PHP

Source: Internet
Author: User
Tags error handling php code

The Set_error_handler () function sets the user-defined error-handling function. This function is used to create the user's own error handling for the Run-time period. The function returns the old error handler, or null if it fails. Let's take a look at some examples.




Set_error_handler ()


 


PHP provides a functional function Set_error_handler () of custom error handling handles from 4.1.0, but very few scripting people know. Set_error_handler This function is a good way to prevent the wrong path from leaking, and of course, there are other effects.


 


1. Can be used to mask errors. An error can cause some information to be leaked to the user, which is very likely to become a tool for hackers attacking your site. Secondly let the user feel your level is very frustrated.


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


3. Can do the corresponding processing, error can show jump to a predefined error page, provide a better user experience.


4. As a debugging tool, some things have to be debugged in a production environment, but you don't want to affect the users you are using.


5 ...

The use of
Set_error_handler is as follows:


 


View sourceprint?1 string Set_error_handler (callback Error_Handler [, int error_types])


 


 


 


We use error_reporting () to see the error message includes three parts, error messages, the absolute address of the error file, the number of errors occurred. In fact, there is 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 is best not to expose to others, otherwise to some people can be called the machine, in order to eliminate this, many people will adopt, Ini_set ("Display_errors", 0); Directly to the wrong message to screen out. This is not convenient, if we want to look at information to do? Every time you look at it, are you going to change the code, or do you want to change the configuration of Apache, in a heavy start?


 


PHP has function set_error_handler can solve this problem


 


usage is as follows:


 


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


 


PHP function register_shutdown_function can also solve this problem


 


usage is as follows:


 


int register_shutdown_function (string $func)


 


personally feel that the error function defines itself, at least three points of benefit,


 


1 does not show the absolute path of the file, it is safe to


 


2, even if there is an error message, we can handle the error message, so that users do not see fatal error such things. The user experience is better


 


3, the project on the line, sometimes, you still have 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.


 


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 "<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";


break;


 


Case e_user_warning:


echo "<b>my warning</b> [$errno] $errstr <br/>n";


echo "Warning on line $errline in file $errfile";


echo ", PHP". Php_version. " (" . Php_os. ") <br/>n";


break;


 


Case E_user_notice:


echo "<b>my notice</b> [$errno] $errstr <br/>n";


echo "Notice on line $errline in file $errfile";


echo ", PHP". Php_version. " (" . Php_os. ") <br/>n";


break;


 


Default:


echo "Unknown error type: [$errno] $errstr <br/>n";


echo "Warning on line $errline in file $errfile";


echo ", PHP". Php_version. " (" . Php_os. ") <br/>n";


break;


  }


 


return true;


 }





class SomeClass {


Public Function SomeMethod () {


 


 }


 }


 


Someclass::somemedthod ();


 


$a = "asdf";


foreach ($a as $d) {


Echo $d;


 }


?>


 


now we're going to filter out the actual path using custom error handling. Suppose there is a variable $admin, we are used to determine whether the visitor is an administrator (you can do this by IP or by the user ID of the login)


 


//admin is the administrator's identity, true to 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 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 Administrator.  ";


//Exit script when error level is encountered


exit;


break;


 


Case e_warning:


echo "WARNING: [ID $errno] $errstr (line: $errline of $errfile) n";


break;


 


Default:


//Does not display notice-level errors


break;


    } 


}


 


This allows you to customize an error handler, so how do you give the wrong handling to this custom function?


 


//Apply to class


Set_error_handler (Array (& $this, "Apperror"));


 


//Examples of practices


Set_error_handler ("My_error_handler");


So easy, this can be a good solution to security and debugging convenience contradictions. And you can also spend some thought, make the error hint more beautiful to match the website style.
 
 
 
In the example above, I turned the error message off and handled the error with my own function, and the page above would report fatal error. We can use ErrorHandler to control and deal with the wrong message.
&NBSP
Well, to summarize, here are Set_error_handler three uses:
 
PHP code
 class callbackclass {
  function Callbackfunction () {
 //refers to $this
 }
 
Function staticfunction () {
&nbs p;//doesn ' t refer to $this
 
 }
 
function nonclassfunction ($errno, $errstr, $errfile, $e Rrline) {
 }
 
//Three methods are as follows:
 
1:set_error_handler (' nonclassfunction ');//go directly to an ordinary function N Onclassfunction
 
2:set_error_handler (Array (' Callbackclass ', ' staticfunction '));//Go to Callbackclass The static method under Class Staticfunction
 
3: $o =& new Callbackclass (),
 set_error_handler ($o, ' Callbackfunction ')); Go to the constructor of a class, essentially the same as the fourth 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.