Given the following two methods for setting a HTTP response code in PHP (specifically, under Apache):
Method 1:
http_response_code(404);
Method 2:
header("HTTP/1.0 404 Not Found");
My questions are:
http_response_code
is only available in PHP 5.4 or greater, what are the differences between the two approaches and why/when to use one over the other?Since I'm being downvoted into oblivion for no apparent reason, I've managed to answer this myself by scouring through the PHP source code. Hopefully this serves as a reference for anyone else trying to work this out.
The two methods are essentially functionally equivalent. http_response_code
is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h.
Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header
method. Note also that http_response_code
is only available in PHP 5.4.0 and higher.
In summary - The differences between http_response_code
and header
for setting response codes:
Using http_response_code
will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.
Because of point 1 above, if you use http_response_code
you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header
function.
http_response_code
is only available in PHP 5.4.0 and higher