PHP $http_response_header

The $http_response_header superglobal array is automatically populated with HTTP response headers when using HTTP wrapper functions like file_get_contents(). This array is created in the local scope where the HTTP request is made.

Syntax

The array is automatically created after calling HTTP wrapper functions −

file_get_contents($url);
// $http_response_header is now available

Example

Here's how to access HTTP response headers using $http_response_header ?

<?php
// Make an HTTP request
$content = file_get_contents("http://localhost");

// Access the response headers
$headers = $http_response_header;

// Display all headers
foreach ($headers as $key => $value) {
    echo "<p>$key => $value</p>";
}
?>

Output

The browser will display headers similar to the following −

0 => HTTP/1.1 302 Found
1 => Date: Tue, 08 Sep 2020 14:49:24 GMT
2 => Server: Apache/2.4.41 (Win64) OpenSSL/1.0.2s PHP/7.1.32
3 => X-Powered-By: PHP/7.1.32
4 => Location: http://localhost/dashboard/
5 => Content-Length: 0
6 => Connection: close
7 => Content-Type: text/html; charset=UTF-8
8 => HTTP/1.1 200 OK
9 => Date: Tue, 08 Sep 2020 14:49:24 GMT
10 => Server: Apache/2.4.41 (Win64) OpenSSL/1.0.2s PHP/7.1.32
11 => Last-Modified: Mon, 02 Sep 2019 15:45:31 GMT
12 => ETag: "1d99-59193dc9c3cc0"
13 => Accept-Ranges: bytes
14 => Content-Length: 7577
15 => Connection: close
16 => Content-Type: text/html

Key Points

  • The array is only available after making an HTTP request using functions like file_get_contents()
  • Headers are stored as indexed array elements (0, 1, 2, etc.)
  • Both redirect (302) and final response (200) headers are included
  • The array exists only in the local scope where the HTTP request was made

Conclusion

The $http_response_header superglobal provides easy access to HTTP response headers after making requests with PHP's HTTP wrapper functions. It's particularly useful for debugging HTTP communications and handling redirects.

Updated on: 2026-03-15T09:26:05+05:30

739 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements