Home  >  Article  >  Backend Development  >  Summary of usage of set error handler function in PHP

Summary of usage of set error handler function in PHP

高洛峰
高洛峰Original
2017-01-06 14:09:491132browse

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. This function returns the old error handler, or null on failure.

Let’s look at some examples.

set_error_handler()

PHP has provided the function set_error_handler() of a custom error handling handle since 4.1.0, but few script writers know it. The set_error_handler function can prevent error paths from being leaked, and of course has other functions.

1. Can be used to mask errors. If an error occurs, some information will be exposed to users, and it is very likely to become a tool for hackers to attack your website. Second, it makes users feel that your level is very low.

2. You can write down error information and discover some problems in the production environment in time.

3. Corresponding processing can be done. When an error occurs, a jump to a predefined error page can be displayed to provide a better user experience.

4. It can be used as a debugging tool. Sometimes it is necessary to debug something in the production environment, but you do not want to affect the users who are using it.

5. . . .

The method of using set_error_handler is as follows:

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

The error message we see using error_reporting(); includes three parts, the error message, the absolute address of the error file, and the number of lines where the error occurred. In fact, there is another type of error. 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, otherwise it will give some people an opportunity to complain. In order to prevent this, many people will use ini_set("display_errors",0); to directly block the error message. This is inconvenient. What if we want to read the information? Do I need to change the code every time I check it, or change the configuration of apache and restart it?

php has the function set_error_handler to solve this problem

The 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

The usage is as follows:

int register_shutdown_function (string $func)

Personally, I feel that defining the error reporting function by yourself has at least three advantages.

1. The absolute path of the file will not be displayed, which is safer.

2, even if an error message does appear, we can process the error message so that users cannot see such things as fatal errors. The user experience must be good

3. After the project is launched, sometimes you still have to help users solve problems. At this time, it is inevitable to modify the code, but we also need to report error messages, and It cannot be seen by users. At this time, it is very cool to use a function like set_error_handler.

I did a small test

<?php
 error_reporting(0);
register_shutdown_function(&#39;error_alert&#39;);
 function error_alert()
 {
 if(is_null($e = error_get_last()) === false)
 {
 set_error_handler(&#39;errorHandler&#39;);
 if($e[&#39;type&#39;] == 1){
 trigger_error("fatal error", E_USER_ERROR);
 }elseif($e[&#39;type&#39;] == 8){
 trigger_error("notice", E_USER_NOTICE);
 }elseif($e[&#39;type&#39;] == 2){
 trigger_error("warning", E_USER_WARNING);
 }else{
 trigger_error("other", E_USER_OTHER);
 }
 }else{
 echo "no error";
 }
 }
 set_error_handler(&#39;errorHandler&#39;);
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 use custom error handling to filter out the actual path. Suppose there is a variable $admin, which we use to determine whether the visitor is an administrator (this determination can be made by IP or logged in user ID)

//admin is the identity of the administrator Determination, true is the administrator.
//The custom error handling function must have these four input variables $errno, $errstr, $errfile, $errline, otherwise it will be invalid.

function my_error_handler($errno,$errstr,$errfile,$errline) 
{ 
  //如果不是管理员就过滤实际路径 
  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 "程序已经停止运行,请联系管理员。"; 
    //遇到Error级错误时退出脚本 
    exit; 
    break; 
    case E_WARNING: 
    echo "WARNING: [ID $errno] $errstr (Line: $errline of $errfile) n"; 
    break; 
    default: 
    //不显示Notice级的错误 
    break; 
  } 
}

In this way, an error handling function is customized, so how to hand over error processing to this custom function?

// 应用到类 
set_error_handler(array(&$this,"appError")); 
//示例的做法 
set_error_handler("my_error_handler");

so easy, in this way, the contradiction between security and debugging convenience can be well solved. And you can also put some thought into making the error message more beautiful to match the style of the website.

In the above example, I turned off the error message and used my own function to handle the error. The page above will report a fatal error. We can use errorHandler to report the error message. Control and processing.

Okay, to summarize, here are the three usages of set_error_handler:

Php code

class CallbackClass {
 function CallbackFunction() {
 // refers to $this
 }
  
function StaticFunction() {
 // doesn&#39;t refer to $this
 }
 }
  
function NonClassFunction($errno, $errstr, $errfile, $errline) {
 }
 // 三种方法如下:
  
 set_error_handler(‘NonClassFunction&#39;); // 直接转到一个普通的函数 NonClassFunction
 set_error_handler(array(‘CallbackClass&#39;, ‘StaticFunction&#39;)); // 转到 CallbackClass 类下的静方法 StaticFunction
 $o =& new CallbackClass();
 set_error_handler(array($o, ‘CallbackFunction&#39;)); // 转到类的构造函数,其实本质上跟下面的第四条一样。
. $o = new CallbackClass();
// The following may also prove useful
class CallbackClass {
 function CallbackClass() {
 set_error_handler(array(&$this, ‘CallbackFunction&#39;)); // the & is important
 }
function CallbackFunction() {
 // refers to $this
 }
 }

Let me take some time to introduce PHP separately. set_error_handler() function

Definition and usage

set_error_handler() function sets a user-defined error handling function.

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

This function will return the old error handler, or null if it fails.

Syntax

set_error_handler(error_function,error_types)

Parameter Description

error_function Required. Specifies the function to run when an error occurs.
error_types Optional. Specifies at which error reporting level user-defined errors are displayed. The default is "E_ALL".

Tips and Notes

Tip: If this function is used, the standard PHP error handling function will be completely bypassed. If necessary, the user-defined error handler must terminate (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

<?php
//error handler function
function customError($errno, $errstr, $errfile, $errline)
 { 
 echo "<b>Custom error:</b> [$errno] $errstr<br />";
 echo " Error on line $errline in $errfile<br />";
 echo "Ending Script";
 die();
 }
//set error handler
set_error_handler("customError");
$test=2;
//trigger error
if ($test>1)
 {
 trigger_error("A custom error has been triggered");
 }
?>

输出:

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

更多PHP中set error handler函数用法小结相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn