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!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor