Setting HTTP response code in PHP (under Apache)

Given the following two methods for setting the 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:

  • Besides the fact that http_response_code is only available in PHP 5.4 or higher, what are the differences between the two approaches and why / when to use one over the other?
  • Where does the reason for the phrase come from when using the first example? (I checked, and from somewhere the phrase of reason is generated)
+4
php apache
source share
1 answer

Since I forgot about oblivion for no apparent reason, I was able to answer this by combing through the PHP source code. I hope this will serve as a benchmark for those who are trying to solve this.

The two methods are essentially functionally equivalent. http_response_code is basically an abbreviated way to write an http status header, with an added bonus, which PHP will develop a suitable "phrase of the mind" to provide by matching your response code with one of the values ​​in the enum that it supports in php-src / main / http_status_codes .h .

Please note that this means that your response code must match the response code that PHP knows about. You cannot create your own response codes using this method, however you can use the header method. Also note that http_response_code is only available in PHP version 5.4.0 and higher.

In general, there are differences between http_response_code and header for setting response codes:

  • Using http_response_code will cause PHP to match and apply the mind phrase from the list of mind phrases that are hard-coded into the PHP source code.

  • Due to paragraph 1 above, if you use http_response_code , you must install the code that PHP knows about. You cannot set your own code, however you can set your own code (and the sentence of reason) if you use the header function.

  • http_response_code is only available in PHP 5.4.0 and later

+8
source

All Articles