


Introduction to Error handling and problem location under PHP5 (code example)
This article brings you an introduction to Error handling and problem location under PHP5 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
Let’s talk about the problem locating method when PHP encounters an E_ERROR level fatal runtime error. For example, Fatal error: Allowed size memory of
memory overflow. When this kind of error occurs, the program will exit directly. An error log will be recorded in PHP's error log indicating the specific file and number of lines of code where the error was reported, and no other information will be lost. If it is PHP7, you can catch errors like exceptions, but not with PHP5.
The generally thought of method is to look at the specific code of the error report. If the error file is CommonReturn.class.php, it will look like the following.
<?php /** * 公共返回封装 * Class CommonReturn */ class CommonReturn { /** * 打包函数 * @param $params * @param int $status * * @return mixed */ static public function packData($params, $status = 0) { $res['status'] = $status; $res['data'] = json_encode($params); return $res; } }
The json_encode line reported an error, and then you checked the packData method. There are many project classes that call it. How to locate the problem?
Scene Reproduction
Okay, first let’s reproduce the scene. If the actually called program bug.php is as follows
<?php require_once './CommonReturn.class.php'; $res = ini_set('memory_limit', '1m'); $res = []; $char = str_repeat('x', 999); for ($i = 0; $i < 900 ; $i++) { $res[] = $char; } $get_pack = CommonReturn::packData($res); // something else
When running bug.php, the PHP error log will record
[08-Jan-2019 11:22:52 Asia/Shanghai] PHP Fatal error: Allowed memory size of 1048576 bytes exhausted (tried to allocate 525177 bytes) in /CommonReturn.class.php on line 20
that the reproduction was successful. The error log only explains the file and line of code where the error was reported. , it is impossible to know the context stack information of the program, and does not know which piece of business logic is called, so it is impossible to locate and fix the error. How to troubleshoot if it occurs occasionally and there is no feedback from the front-end business.
Solution ideas
1. Some people thought of modifying memory_limit to increase memory allocation, but this method treats the symptoms but not the root cause. When doing development, you must find the root cause of the problem.
2. Turn on core dump. If the code file is generated, it can be debugged. However, it is found that the code will only be generated when the process exits abnormally. Errors at the E_ERROR level may not necessarily generate code files. The possibility of memory overflow is handled by PHP internally.
3. Use register_shutdown_function to register a callback function when PHP terminates, and then call error_get_last. If the last error that occurred is obtained, use debug_print_backtrace to obtain the stack information of the program. Let's try it.
Modify the CommonReturn.class.php file as follows
<?php /** * 公共返回封装 * Class CommonReturn */ class CommonReturn { /** * 打包函数 * @param $params * @param int $status * * @return mixed */ static public function packData($params, $status = 0) { register_shutdown_function(['CommonReturn', 'handleFatal']); $res['status'] = $status; $res['data'] = json_encode($params); return $res; } /** * 错误处理 */ static protected function handleFatal() { $err = error_get_last(); if ($err['type']) { ob_start(); debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5); $trace = ob_get_clean(); $log_cont = 'time=%s' . PHP_EOL . 'error_get_last:%s' . PHP_EOL . 'trace:%s' . PHP_EOL; @file_put_contents('/tmp/debug_' . __FUNCTION__ . '.log', sprintf($log_cont, date('Y-m-d H:i:s'), var_export($err, 1), $trace), FILE_APPEND); } } }
Run bug.php again, the log is as follows.
error_get_last:array ( 'type' => 1, 'message' => 'Allowed memory size of 1048576 bytes exhausted (tried to allocate 525177 bytes)', 'file' => '/CommonReturn.class.php', 'line' => 23, ) trace:#0 CommonReturn::handleFatal()
The traceback information has no source, which is embarrassing. I guess because the backtrace information is stored in memory and will be cleared when a fatal error occurs. There is no other way, try passing the backtrace in from the outside. Modify CommonReturn.class.php again.
<?php /** * 公共返回封装 * Class CommonReturn */ class CommonReturn { /** * 打包函数 * @param $params * @param int $status * * @return mixed */ static public function packData($params, $status = 0) { ob_start(); debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5); $trace = ob_get_clean(); register_shutdown_function(['CommonReturn', 'handleFatal'], $trace); $res['status'] = $status; $res['data'] = json_encode($params); return $res; } /** * 错误处理 * @param $trace */ static protected function handleFatal($trace) { $err = error_get_last(); if ($err['type']) { $log_cont = 'time=%s' . PHP_EOL . 'error_get_last:%s' . PHP_EOL . 'trace:%s' . PHP_EOL; @file_put_contents('/tmp/debug_' . __FUNCTION__ . '.log', sprintf($log_cont, date('Y-m-d H:i:s'), var_export($err, 1), $trace), FILE_APPEND); } } }
Run bug.php
again, the log is as follows.
error_get_last:array ( 'type' => 1, 'message' => 'Allowed memory size of 1048576 bytes exhausted (tried to allocate 525177 bytes)', 'file' => '/CommonReturn.class.php', 'line' => 26, ) trace:#0 CommonReturn::packData() called at [/bug.php:13]
Successfully located the source of the call, which is on line 13 of bug.php. Publish the final CommonReturn.class.php to the production environment, and just look at the log when an error occurs again. But in this case, all programs that call packData will execute the trace function, which will definitely affect performance.
Summary
You need to pay attention to the register_shutdown_function function used. You can register multiple different callbacks, but if a certain callback function If you exit, any callback functions registered later will not be executed.
debug_print_backtrace This function to obtain backtrace information first contains request parameters, and the second is the number of backtrace record levels. We do not return request parameters here, which can save some memory, and if If the request parameters are huge, calling this function may cause memory overflow.
The best way is to upgrade PHP7, which can catch errors like exceptions.
The above is the detailed content of Introduction to Error handling and problem location under PHP5 (code example). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
