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?
Yeah, just do this...
The first string parameter can be anything that doesn't contain a
:
. PHP will then replace and go with the standard phrase. The second parameter specifies "always replace", and the 3rd is the status code you want.References:
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:
Zend Framework has a packaged solution in
Zend_Http_Response
Zend_Http_Response::$messages
contains:Even if you're not using zend-framework you might be able to break this out for personal use.
The actual text of the code is irrelevant. You could do
and it'd still be seen as a 404 by the browser - it's the code that matters.