When working with APIs or external resources in PHP, sometimes you need to inspect the HTTP response headers — not just the content. While cURL is commonly used for this, you can also retrieve headers using the built-in file_get_contents()
function with the right stream context.
In this post, we learn the effective way to get response headers, while using PHP file_get_contents()
function.
Using $http_response_header
PHP variable to Get Response Headers
$http_response_header
We use file_get_contents()
to fetch the content from a URL. But with some configuration, you can also access the response headers.
Here’s how you can do it:
<?php
$url = "https://example.com";
// Create a stream context
$options = [
"http" => [
"method" => "GET",
"header" => "User-Agent: PHP\r\n"
]
];
$context = stream_context_create($options);
// Fetch the content
$response = file_get_contents($url, false, $context);
// Display the content
echo $response;
// Get the response headers
print_r($http_response_header);
?>
Explanation
- We used
stream_context_create()
to define HTTP request options, like headers or methods. - The
$http_response_header
is a special PHP variable automatically populated when usingfile_get_contents()
with an HTTP context. - It contains the raw headers returned by the server as an indexed array.
Example Output
When you run the above script, $http_response_header
might contain something like:
Array
(
[0] => HTTP/1.1 200 OK
[1] => Content-Type: text/html; charset=UTF-8
[2] => Date: Wed, 25 Jun 2025 10:30:00 GMT
...
)
Checking Specific Headers
You can loop through the headers to extract specific values:
foreach ($http_response_header as $header) {
if (stripos($header, "Content-Type:") !== false) {
echo "Content-Type Header: $header";
}
}
Use Cases
We can use this method for various purpose as follows:
- Verifying HTTP status codes
- Checking content type or caching headers
- Basic debugging of server responses without using cURL
Conclusion
While file_get_contents()
is often seen as a simple way to read data from URLs, it’s surprisingly powerful when paired with stream contexts. For lightweight HTTP requests where you don’t need advanced control, it’s a quick alternative to cURL — and retrieving headers is straightforward using $http_response_header
.