Share via:

Http_response_code vs Header

Article documenting the reasons to use Http_response_code instead of sending raw HTTP response codes in PHP.


Edited: 2020-01-05 02:47

The main benefit of using the http_response_code function, is that we can send HTTP response codes, without having to think about the protocol version used by the client. If instead we send raw response codes with the PHP header function, we will need to manually determine the protocol version.

Many PHP applications will incorrectly send a raw HTTP header response code, without properly determining the protocol the client is using. This can, in rare cases lead to problems.

Hard-coding the protocol, such as HTTP/2.0 or HTTP/1.1, is bad and unnecessary. Instead, we should allow PHP to determine the protocol automatically. When using the http_response_code function, we do not have these issues.

echo '<p>Hallo World!</p>';

Another benefit is that you minimize risk of misspelling the response header field.

Sending raw HTTP headers with PHP

If you still want to send raw headers, be sure to use a function like the below to determine the HTTP protocol version used by the client:

function set_protocol() {
  $supported_protocols = array(
    'HTTP/2.0' => true,
    'HTTP/1.1' => true,
    'HTTP/1.0' => true,
  $protocol = $_SERVER["SERVER_PROTOCOL"];
  if (!isset($supported_protocols["$protocol"])) {
    $protocol = 'HTTP/1.0';
  return $protocol;