Best way to send HTTP response code in PHP

From reading the php specification and other stack overflow questions, I see three ways to send HTTP response code from PHP:

header("HTTP/1.0 404 Not Found"); ^ ^ ^ ABC header(" ", false, 404); ^ ^ ^ CDB http_response_code(404); ^ B A: Defines HTTP header B: Response code C: Message D: To replace previous header or not 

What is the difference between them and which one is the best to use? Do I understand the parameters correctly?

Thanks,

Tugzrida.

+5
source share
1 answer

To answer the question of what the difference is, I found this comment in PHP docs (thanks to Stephen):

http_response_code is basically an abbreviated way of writing an http status header with an added bonus that PHP will develop a suitable phrase for the reason to provide by matching your response code with one of the values ​​in the listing that it supports inside PHP-SRC / Master / 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 using this method, however you can use the header method.

Finally. 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 method.


I was wondering how some popular frameworks send a header to the standard answer:

Symfony (and Laravel , by inheritance) sets the original header:

 // status header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode); 

Zend Framework 2 also sets the source header:

 public function renderStatusLine() { $status = sprintf( 'HTTP/%s %d %s', $this->getVersion(), $this->getStatusCode(), $this->getReasonPhrase() ); return trim($status); } 

Also Yii

 protected function sendHeaders() { if (headers_sent()) { return; } $statusCode = $this->getStatusCode(); header("HTTP/{$this->version} $statusCode {$this->statusText}"); // ... 
+3
source

All Articles