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

Jan 06, 2017 pm 02:09 PM

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])
Copy after login

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

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

输出:

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles