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

后端 未结 10 1435
孤独总比滥情好
孤独总比滥情好 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 11:09

    Never forget to set header("HTTP/1.1 200 OK", true, 200); as the last line of any execution path:

    //first things first:
    header("HTTP/1.1 500 Internal Server Error", true, 500);
    
    
    //Application code, includes, requires, etc. [...]
    
    
    //somewhere something happens
    //die();
    throw new Exception("Uncaught exception!");
    
    
    //last things last, only reached if code execution was not stopped by uncaught exception or some fatal error
    header("HTTP/1.1 200 OK", true, 200);
    

    In PHP 5.4 you can replace the header function above with the much better http_response_code(200) or http_response_code(500).

    0 讨论(0)
  • 2020-12-24 11:09

    The hard thing when dealing with fatal errors (compile errors, for example a missing semicolon) is that the script won't be executed, so it won't help to set the status code in that script. However, when you include or require a script, the calling script will be executed, regardless of errors in the included script. With this, I come to this solution:

    rock-solid-script.php:

    // minimize changes to this script to keep it rock-solid
    http_response_code(500); // PHP >= 5.4
    require_once("script-i-want-to-guard-for-errors.php");
    

    script-i-want-to-guard-for-errors.php:

    // do all the processsing
    // don't produce any output
    // you might want to use output buffering
    
    http_response_code(200); // PHP >= 5.4
    
    // here you can produce the output
    

    Direct your call to the rock-solid-script.php and you're ready to go.

    I would have liked it better to set the default status code to 500 in .htaccess. That seems more elegant to me but I can't find a way to pull it off. I tried the RewriteRule R-flag, but this prevents execution of php altogether, so that's no use.

    0 讨论(0)
  • 2020-12-24 11:10

    I have used "set_exception_handler" to handle uncaught exceptions.

    function handleException($ex) {
          error_log("Uncaught exception class=" . get_class($ex) . " message=" . $ex->getMessage() . " line=" . $ex->getLine());
          ob_end_clean(); # try to purge content sent so far
          header('HTTP/1.1 500 Internal Server Error');
          echo 'Internal error';
        }
    
    set_exception_handler('handleException');
    
    0 讨论(0)
  • 2020-12-24 11:16
    header("HTTP/1.1 500 Internal Server Error");
    
    0 讨论(0)
提交回复
热议问题