Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
NikiC Avatar asked Jan 25 '11 18:01

NikiC


People also ask

How are status codes grouped?

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.

Which HTTP status code do you receive for a non existing page?

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.

Which HTTP status code is to be used when a resource is created successfully?

The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource.


1 Answers

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'); 
like image 56
hectorct Avatar answered Oct 03 '22 01:10

hectorct