How can I get php to return 500 upon encountering a fatal exception?

后端 未结 10 1492
孤独总比滥情好
孤独总比滥情好 2020-12-24 10:37

PHP fatal errors come back as status code 200 to the HTTP client. How can I make it return a status code 500 (Internal server error)?

10条回答
  •  眼角桃花
    2020-12-24 10:59

    This is exactly the problem I had yesterday and I found solution as follows:

    1) first of all, you need to catch PHP fatal errors, which is error type E_ERROR. when this error occurs, script will be stored the error and terminate execution. you can get the stored error by calling function error_get_last().

    2) before script terminated, a callback function register_shutdown_function() will always be called. so you need to register a error handler by this function to do what you want, in this case, return header 500 and a customized internal error page (optional).

    function my_error_handler()
    {
      $last_error = error_get_last();
      if ($last_error && $last_error['type']==E_ERROR)
          {
            header("HTTP/1.1 500 Internal Server Error");
            echo '...';//html for 500 page
          }
    }
    register_shutdown_function('my_error_handler');
    

    Note: if you want to catch custom error type, which start with E_USER*, you can use function set_error_handler() to register error handler and trigger error by function trigger_error, however, this error handler can not handle E_ERROR error type. see explanation on php.net about error handler

提交回复
热议问题