Table of Contents
set_error_handler()
Home Backend Development PHP Tutorial Use of PHP set_error_handler() function_PHP tutorial

Use of PHP set_error_handler() function_PHP tutorial

Jul 13, 2016 am 10:34 AM
set_error_handler Report an error

When we write programs, there will inevitably be problems (problems are often encountered), and when PHP encounters an error, it will give the location, line number and reason of the error script. A lot of people say it's not a big deal. Indeed, in the debugging phase, this really doesn't matter, and I think giving the error path is necessary.

But the consequences of leaking the actual path are unimaginable. For some intruders, this information is very important. In fact, many servers now have this problem. Some network administrators simply set display_errors in the PHP configuration file to Off to solve the problem (it seems like we did this), but I think this method is too negative.

Sometimes, we really need PHP to return error information for debugging. And when something goes wrong, you may also need to give the user an explanation or even navigate to another page.

So, what’s the solution?

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 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 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:

1

string set_error_handler ( callback error_handler [, int error_types])

Copy after login

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)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

//admin为管理员的身份判定,true为管理员。 

//自定义的错误处理函数一定要有这4个输入变量$errno,$errstr,$errfile,$errline,否则无效。 

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 error handling to this custom function?

1

2

3

4

5

// 应用到类 

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.

The original author gave two points that need attention. I will also post them, hoping to attract the attention of our compatriots:

  1. E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING will not be processed by this handle, that is, they will be displayed in the most original way. However, these errors are caused by compilation or PHP kernel errors and will not occur under normal circumstances.
  2. After using set_error_handler(), error_reporting () will be invalid. That is, all errors (except the above errors) will be handed over to the custom function for processing.

Finally, the original author gave another example (he is such a serious and responsible person.)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

//先定义一个函数,也可以定义在其他的文件中,再用require()调用 

function myErrorHandler($errno, $errstr, $errfile, $errline

     //为了安全起见,不暴露出真实物理路径,下面两行过滤实际路径 

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

   

//下面开始连接MYSQL服务器,我们故意指定MYSQL端口为3333,实际为3306。 

$link_id=@mysql_pconnect("localhost:3333","root","password"); 

set_error_handler(myErrorHandler); 

if (!$link_id) { 

    trigger_error("出错了", E_USER_ERROR); 

Copy after login

Okay, to summarize, here are three uses of set_error_handler:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

class CallbackClass { 

   function CallbackFunction() { 

       // refers to $this 

   

   

   function StaticFunction() { 

       // doesn't refer to $this 

   

   

function NonClassFunction($errno, $errstr, $errfile, $errline) { 

   

// 三种方法如下: 

   

1: set_error_handler('NonClassFunction');  // 直接转到一个普通的函数 NonClassFunction 

   

2: set_error_handler(array('CallbackClass', 'StaticFunction')); // 转到 CallbackClass 类下的静方法 StaticFunction 

   

3: $o =& new CallbackClass(); 

    set_error_handler(array($o, 'CallbackFunction'));  // 转到类的构造函数,其实本质上跟下面的第四条一样。 

   

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 

   

Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752326.htmlTechArticleWhen we write programs, it is inevitable that there will be problems (problems are often encountered), and when PHP encounters errors, The location, line number and reason of the error script will be given. Many people say that this is nothing...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Column count doesn't match value count at row 1 - How to solve MySQL error: column number does not match value Column count doesn't match value count at row 1 - How to solve MySQL error: column number does not match value Oct 05, 2023 am 11:40 AM

How to solve MySQL error: The number of columns does not match the value. Specific code examples are needed. When using the MySQL database for data operations, sometimes you will encounter the error message: "Columncountdoesn'tmatchvaluecountatrow1", which means that the number of columns does not match the number of values. match. This error usually occurs when inserting data and the number of columns specified is inconsistent with the number of values ​​inserted. This article describes specific workarounds and provides code examples. examine

mysql error 10060 mysql error 10060 Sep 12, 2023 am 11:00 AM

The solutions to mysql error 10060 include checking whether the MySQL server is running normally, checking the network connection, checking the firewall settings, checking the MySQL server configuration, checking the MySQL user permissions, checking the network configuration, checking the maximum number of connections limit of the MySQL server, and using the IP address instead of the host. Name and restart the MySQL server, etc. Detailed introduction: 1. Check whether the MySQL server is running normally. First, make sure the MySQL server is running and listening to the correct port, etc.

Incorrect table definition; there can be only one auto column and it must be defined as a key - How to solve MySQL error: Incorrect table definition; there can be only one auto column and it must be defined as a key Incorrect table definition; there can be only one auto column and it must be defined as a key - How to solve MySQL error: Incorrect table definition; there can be only one auto column and it must be defined as a key Oct 05, 2023 am 11:05 AM

How to solve MySQL error: Wrong table definition; there can only be one automatic column and it must be defined as a key. Specific code examples are required. In recent years, MySQL database has become more and more widely used, but during use, we often encounter Various error reports. Among them, a common error is "wrong table definition; there can only be one automatic column and it must be defined as a key". This error usually occurs when we create a table, which may be a headache for beginners. This article will give you a detailed analysis of the reasons for this error and provide specific

Cause analysis: HTTP request error 504 gateway timeout Cause analysis: HTTP request error 504 gateway timeout Feb 19, 2024 pm 05:12 PM

Brief introduction to the reason for the http request error: 504GatewayTimeout: During network communication, the client interacts with the server by sending HTTP requests. However, sometimes we may encounter some error messages during the process of sending the request. One of them is the 504GatewayTimeout error. This article will explore the causes and solutions to this error. What is the 504GatewayTimeout error? GatewayTimeo

Solution: Socket Error when handling HTTP requests Solution: Socket Error when handling HTTP requests Feb 25, 2024 pm 09:24 PM

http request error: Solution to SocketError When making network requests, we often encounter various errors. One of the common problems is SocketError. This error is thrown when our application cannot establish a connection with the server. In this article, we will discuss some common causes and solutions of SocketError. First, we need to understand what Socket is. Socket is a communication protocol that allows applications to

Step-by-step guide to quickly solve pyqt5 installation errors Step-by-step guide to quickly solve pyqt5 installation errors Jan 19, 2024 am 09:32 AM

If you are learning Python and want to develop GUI applications, PyQt5 is a very good choice. It is a bound version of the PyQt library under Python, which makes it very convenient to call and develop the Qt graphics library. However, sometimes you may encounter some problems when installing PyQt5. This guide will provide you with some steps to quickly solve installation error problems, and also attach specific code examples. Make sure the Python version is correct PyQt5 is a Python-based library, so first

Unknown column 'column_name' in 'where clause' - How to solve MySQL error: unknown column in where clause Unknown column 'column_name' in 'where clause' - How to solve MySQL error: unknown column in where clause Oct 05, 2023 am 11:15 AM

Unknowncolumn'column_name'in'whereclause'-How to solve MySQL error: unknown column in where clause, specific code example is needed MySQL is a widely used relational database management system, which supports the use of Structured Query Language (SQL) Storage, management and retrieval of data. However, when using MySQL to query, sometimes we will encounter errors. One of the common errors is: Unkno

Incorrect syntax near 'error_keyword' - How to solve MySQL error: syntax error Incorrect syntax near 'error_keyword' - How to solve MySQL error: syntax error Oct 05, 2023 pm 04:24 PM

Errors are one of the problems that developers often encounter when writing MySQL query statements. One of the common errors is "Incorrectsyntaxnear 'error_keyword'" (Syntax error near 'error_keyword'). This error message is very common and means that there is a syntax error in the MySQL query statement. In this article, we'll detail how to solve this problem and provide some concrete code examples. First, let's look at

See all articles