Home >Backend Development >PHP Problem >How to solve php 500 error problem

How to solve php 500 error problem

藏色散人
藏色散人Original
2021-12-29 09:30:2912597browse

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.

How to solve php 500 error problem

#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.

How to solve php 500 error problem

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.

How to solve php 500 error problem

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.

How to solve php 500 error problem

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.

How to solve php 500 error problem

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.

How to solve php 500 error problem

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.

How to solve php 500 error problem

Error logging switch

How to solve php 500 error problem

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.

How to solve php 500 error problem

#PHP error log records various types of errors

How to solve php 500 error problem

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!

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