How to return an HTTP 500 code on any error, no matter what

后端 未结 7 844
无人及你
无人及你 2020-12-09 14:35

I\'m writing an authentication script in PHP, to be called as an API, that needs to return 200only in the case that it approves the request, and403(Forbid

相关标签:
7条回答
  • 2020-12-09 14:56

    Use output buffering to allow you to modify the headers after writing to the body of the page. You can set this in the ini file rather than updating every script.

    (Note the header() call will still fail if you explicitly flush the output buffer)

    C.

    0 讨论(0)
  • 2020-12-09 15:02
    header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
    

    You should not use 500, that indicates an internal server error.

    This (and other headers) should be sent before any ouput, except if you have output buffering enabled.

    0 讨论(0)
  • 2020-12-09 15:03

    Curious if you ever figured out how to get PHP to return 500 on Parse errors... I have the same exact need... API is posting to our app and expects a 200 only if everything was processed correctly...

    In the case of a Parse error, PHP returns an Error 200 and I have used both of these functions:

    register_shutdown_function() set_error_handler()

    and these don't get hit when a "parse/syntax" error happens in the code...

    So this is a low-level PHP function that would have to be set in the PHP.INI or somewhere... I am using PHP 5.3.10...

    0 讨论(0)
  • 2020-12-09 15:05

    Simply send the status code as a response header():

    header('HTTP/1.1 500 Internal Server Error');
    

    Remember that when sending this there must not be any output before it. That means no echo calls and no HTML or whitespace.

    0 讨论(0)
  • 2020-12-09 15:05

    I checked the PHP docs for header(), and it's simpler than I was making it - if the second parameter is true, it will replace a similar header. the default is true. So the correct behavior is header ('HTTP/1.1 403 Forbidden');, then do the authentication logic, then if it authenticates, do header ('HTTP/1.1 200 OK'). It will replace the 403 response, and will guarantee that 403 is the default.

    0 讨论(0)
  • 2020-12-09 15:17

    Since PHP 5.4.0 there is a specialized function:

    <?php http_response_code( 500 ); ?>
    

    Just make sure that it's called before any other output.

    Reference:

    • https://www.php.net/manual/en/function.http-response-code.php
    0 讨论(0)
提交回复
热议问题