Home > Backend Development > PHP Tutorial > Summary of usage of set error handler() function in php

Summary of usage of set error handler() function in php

怪我咯
Release: 2023-03-12 21:06:02
Original
1125 people have browsed it

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 will return the old error handler, or null if it fails

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.

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 usage method of set_error_handler is as follows:

The code is as follows:

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

We useerror_reporting();The error message you see 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 think there are at least three advantages to defining the error function yourself.


1. It will not change the absolute value of the file The path is 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;
 }
 ?>
Copy after login

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; 
  } 
}
Copy after login

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

custom function?

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

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 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
 }
 }
Copy after login

Let me take some time to introduce to you the PHP set_error_handler() function

Definition and usage

set_error_handler() function to set user-defined settings 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.

grammar

set_error_handler(error_function,error_types)

参数 描述

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");
 }
?>
Copy after login

输出:

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

The above is the detailed content of Summary of usage of set error handler() function in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template