Tugzrida
Tugzrida

Reputation: 521

Best way to send HTTP response code in PHP

From reading the php spec and other questions on Stack Overflow, I can see three ways of sending an HTTP response code from PHP:

header("HTTP/1.0 404 Not Found");
           ^      ^     ^
           A      B     C

header(" ", false, 404);
        ^     ^     ^
        C     D     B

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 these and which one is the best to use? Is my understanding of the parameters correct?

Thanks,

Tugzrida.

Upvotes: 6

Views: 6175

Answers (1)

Jody
Jody

Reputation: 1743

To answer your question about what is the difference, I found this comment in the PHP docs (thanks Steven):

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.

In summary - The differences between http_response_code and header for setting response codes:

  1. 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.

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


I was curious about how some popular frameworks send the header in a standard response:

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

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

Zend Framework 2 also sets the raw header:

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

And so does Yii

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

Upvotes: 3

Related Questions