Home >Backend Development >PHP Tutorial >Summary of usage of set error handler function in PHP, sethandler_PHP tutorial
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 returns the old error handler, or null on failure.
Look at some examples below.
set_error_handler()
PHP has provided the function set_error_handler() to customize error handling handles since 4.1.0, but few script writers know about it. The set_error_handler function can prevent error paths from being leaked, and of course it has other functions.
1. Can be used to block 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 you have to debug something in the production environment, but you don’t want to affect the users who are using it.
5. . . .
The usage of set_error_handler is as follows:
Copy code The code 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
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, I think defining the error function 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. Better user experience
3. After the project goes online, 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 without letting users see them. At this time, It’s great to use functions like set_error_handler.
I did a small 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 use custom error handling to filter out the actual paths. 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 determination of the administrator, 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; } }
This way you have customized an error handling function, so how do you hand over error handling 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 control and handle the reported error message.
Okay, to summarize, here are three usages of 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) { } // 三种方法如下: set_error_handler(‘NonClassFunction'); // 直接转到一个普通的函数 NonClassFunction set_error_handler(array(‘CallbackClass', ‘StaticFunction')); // 转到 CallbackClass 类下的静方法 StaticFunction $o =& new CallbackClass(); set_error_handler(array($o, ‘CallbackFunction')); // 转到类的构造函数,其实本质上跟下面的第四条一样。 . $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 } }
Let me take some time to introduce to you the PHP set_error_handler() function
Definition and Usage
The 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 returns the old error handler, or null on failure.
Grammar
set_error_handler(error_function,error_types)
Parameter Description
error_function 必需。规定发生错误时运行的函数。
error_types 可选。规定在哪个错误报告级别会显示用户定义的错误。默认是 "E_ALL"。
提示和注释
提示:如果使用了该函数,会完全绕过标准的 PHP 错误处理函数,如果必要,用户定义的错误处理程序必须终止 (die() ) 脚本。
注释:如果在脚本执行前发生错误,由于在那时自定义程序还没有注册,因此就不会用到这个自定义错误处理程序。
例子
<?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