Search code examples
phpheaderhttp-status-codes

How to send a status code in PHP, without maintaining an array of status names?


All I want to do, is send a 404 status code from PHP - but in a generic fashion. Both Router::statusCode(404) and Router::statusCode(403) should work, as well as any other valid HTTP status code.

I do know, that you can specify a status code as third parameter to header. Sadly this only works if you specify a string. Thus calling header('', false, 404) does not work.

Furthermore I know, that one can send a status code via a header call with a status line: header('HTTP/1.1 404 Not Found')

But to do this I have to maintain an array of reason phrases (Not Found) for all status codes (404). I don't like the idea of this, as it somehow is a duplication of what PHP already does itself (for the third header parameter).

So, my question is: Is there any simple and clean way to send a status code in PHP?


Solution

  • There is a new function for this in PHP >= 5.4.0 http_response_code

    Simply do http_response_code(404).

    If you have a lower PHP version try header(' ', true, 404); (note the whitespace in the string).

    If you want to set the reason phrase as well try:

    header('HTTP/ 433 Reason Phrase As You Wish');