6

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.

1 Answer 1

3

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}");
    // ...
Sign up to request clarification or add additional context in comments.

1 Comment

As an additional note, I have encountered a scenario under IIS/FastCGI where http_response_code does not work, but you can still set it via header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.