How to solve php 500 error problem
Solution to php 500 error: 1. Check the PHP script and modify it; 2. Capture the exception and record the exception to the log; 3. Analyze the log and process it.
#The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.
How to solve the php 500 error problem?
PHP and 500 error
Returns are often encountered during the PHP development process 500 error situation, and there is no debugging (available) content in the body. At this time, you need to slowly debug (break points, turn on debugging mode, etc.), but if it is a live network, this error is more frustrating. It is neither easy to break points nor turn on debugging mode. But since it is an error, there is always a solution. Let’s analyze the causes and solutions of 500 step by step.
0x01, 500 error
500 error, also called Internal Server Error (internal service error), means that the service cannot process the request due to an unknown error. In PHP sites, it is generally returned by PHP. In other words, 500 errors are generally errors in PHP scripts.
php-fpm capture packet 500
As can be seen from the above figure (Nginx PHP-FPM architecture), a non-existent class is called in PHP When the script occurs, an error occurs and returns 500 to Nginx (and the error message is also returned, but it is unloaded in STDERR).
0x02. Which error exceptions will cause 500
So what kind of errors will cause 500 errors? All PHP error levels can be found in PHP’s official documentation (http ://php.net/manual/zh/errorfunc.constants.php), and the error levels are E_ERROR, E_PARSE, E_RECOVERABLE_ERROR, E_USER_ERROR and uncaught exceptions, etc. will cause 500 errors.
E_ERROR level error causes 500
0x03. Under what circumstances will the error not return 500
above? As mentioned, this is caused by an error in the PHP script, but will an error or exception in the PHP script definitely result in a 500? Obviously not, even if the script has a fatal error, it can still return 200.
display_errors configuration option
In web applications based on python, nodejs, etc., by default, if an exception occurs, the information will be printed to the console ( STDERR/STDOUT). In PHP based on the PHP-FPM architecture, there is no console to print, and its stderr and stdout are set to the corresponding STRDERR and STDOUT in FastCGI. If the error is redirected to STDOUT, the error will be output directly to the response, and the status code will be set to 200. This is also the capability achieved by the display_errors option.
The configuration of the display_errors option needs to be implemented through ini_set. The configuration of display_errors in the PHP document indicates that the value is a string type. In actual use, numbers and Boolean types can also turn this configuration on or off.
error_reporting configuration
display_errors controls whether the error details are displayed and whether the error status code is returned when an error occurs in the PHP script, and the error_reporting item is used to control which Level errors can be printed directly.
The setting items of error_reporting can be configured through error_reporting(E_ALL) or ini_set('error_reporting', E_ALL). For details of function parameters, please refer to the PHP documentation.
It should be noted that PHP itself has error logs (two configuration items error_log and log_errors). If an error occurs, PHP will write the error into the error log, and which errors need to be written. It is controlled by the error_reporting item.
Do not display error details when the error level does not match
0x04. How to handle 500 reasonably on the existing network
The occurrence of the 500 error indicates that the PHP script cannot run normally. All that can be done at this time is to capture the exception and record the exception to the log to facilitate future debugging and processing of live network bugs.
PHP comes with its own error log
PHP itself already has error log records, you can set log_errors in php.ini Set the item to On and cooperate with the error_log configuration item to specify the storage path of the error log.
Error logging switch
Log path setting
The writing of this error log is not affected by display_errors configuration control. That is to say, regardless of whether display_errors is turned on or not, errors will be recorded in the log. However, it is controlled by the error_reporting configuration. If the current error level does not match the error level in error_reporting, the error will not be written to the log. That is, if the error level is E_ERROR, but the setting is error_reporting(E_NOTICE), then the E_ERROR error message will not appear in the log.
#PHP error log records various types of errors
The log is not written due to error level mismatch
Capture error exception records
PHP provides set_error_handler, register_shutdown_function, set_exception_handler, error_get_last and other related error handling functions. Error recording can be achieved by writing the captured error information to the specified log through a function.
For details on the use of functions, please refer to http://km.oa.com/group/19368/articles/show/302491. Here is a template:
$previousHandler = set_exception_handler(function(Exception $ex) use (&$previousHandler) { call_user_func('exceptionHandler', $ex, $previousHandler); }); set_error_handler('errorHandler'); register_shutdown_function('fatalErrorHandler'); function exceptionHandler(Exception $ex, $previousHandler) { $info = array( $ex->getFile(), $ex->getLine(), $ex->getCode(), $ex->getMessage() ); // 记录日志 logPHPError($info); if (isset($previousHandler) && is_callable($previousHandler)) { call_user_func($previousHandler, $ex); } } /** * 框架错误处理函数 * @param $errno * @param $errstr * @param $errfile * @param $errline * @return bool */ function errorHandler($errno = 0, $errstr = '', $errfile = '', $errline = 0) { switch ($errno) { case E_WARNING: $errname = 'E_WARNING'; break; case E_NOTICE: $errname = 'E_NOTICE'; break; case E_STRICT: $errname = 'E_STRICT'; break; case E_RECOVERABLE_ERROR: $errname = 'E_RECOVERABLE_ERROR'; break; case E_DEPRECATED: $errname = 'E_DEPRECATED'; break; case E_USER_ERROR: $errname = 'E_USER_ERROR'; break; case E_USER_WARNING: $errname = 'E_USER_WARNING'; break; case E_USER_NOTICE: $errname = 'E_USER_NOTICE'; break; case E_USER_DEPRECATED: $errname = 'E_USER_DEPRECATED'; break; default: restore_error_handler(); return false; } // 记录日志 $info = array( $errfile, $errline, $errname, $errstr ); logPHPError($info); restore_error_handler(); return false; } /** * Fatal error错误处理 */ function fatalErrorHandler() { if (($e = error_get_last()) && $e['type'] === E_ERROR) { $info = array( $e['file'], $e['line'], 'E_ERROR', $e['message'] ); // 记录日志 logPHPError($info); } }
0x05 Summary
To summarize, error_reporting is a function or configuration used to control the level of error information output to the browser or PHP error log, while display_errors controls whether to output error and warning information to the browser.
Since PHP's error log is global and controlled by error_reporting, it is recommended to implement your own error (exception) capture and recording logic in the business.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to solve php 500 error problem. 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

AI Hentai Generator
Generate AI Hentai for free.

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.
