PHP: apache_response_headers
The apache_response_headers() function allows you to obtain some of the HTTP response headers that are sent by the Apache HTTP server; it does not return all the headers, so it might not do what you expect.
Edited: 2024-03-16 12:09
The apache_response_headers function is used to return certain HTTP response headers that are sent by the Apache web server, but it does not reveal all headers that are controlled by Apache, and therefor may not be very useful.
The function either returns an associative array on success or false on failure; the returned array contains key and value pairs for easy parsing.
Example use:
$apache_headers = apache_response_headers();
var_dump($apache_headers);
Output:
array(2) {
["Upgrade"]=>
string(6) "h2,h2c"
["Connection"]=>
string(7) "Upgrade"
}
Accessing or iterating over the array
You can easily iterate over the array using a foreach loop. E.g:
$response_headers = apache_response_headers();
foreach ($response_headers as $name => $value) {
echo $name . ": ". $value . '<br>';
}
Availability
Because the availability of this function seem to be somewhat inconsistent, it is recommended not to rely on it alone; as a alternative, you can access at least some response headers in the headers_list() function.
You can check if the function is available like this:
if (function_exists('apache_response_headers')) {
$response_headers = apache_response_headers();
} else {
$response_headers = headers_list();
}
You may prefer headers in the form of associative arrays, to get there you can re-shape the output of headers_list():
$response_headers = headers_list();
foreach ($response_headers as $value) {
if(false !== ($matches = explode(':', $value, 2))) {
$headers["{$matches[0]}"] = trim($matches[1]);
}
}
print_r($headers);
Apache_response_headers might be undefined
The official documentation mentions that it should be available, even when using PHP with FastCGI or PHP-FPM, but that does not see to be the case.
Fetch all HTTP response headers. Works in the Apache, FastCGI, CLI, and FPM webservers.
Source: apache_response_headers (php.net)
I tried using it with a configuration of Apache, PHP 8.1 and PHP-FPM and it was not working.
When the function is not available, it may result in an error like this:
Call to undefined function apache_response_headers()
Links
- apache_response_headers - php.net
Tell us what you think: