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?
Status Code Organization100 group: Items in progress. 200 group: Successful responses. 300 group: Redirects, which tell the browser to look someplace else. 400 group: Browser errors, also called client errors.
HTTP Status Code 404 - Not Found This means the file or page that the browser is requesting wasn't found by the server. 404s don't indicate whether the missing page or resource is missing permanently or only temporarily. You can see what this looks like on your site by typing in a URL that doesn't exist.
The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With