Get response headers in PHP from vhost configuration

By | January 12, 2018
Questions:

I have a vhost configuration that has a directive to add a response header to every request, like this:

Header append X-MyHeader "Info Stuff in here"

If I run phpinfo() on this server, I see this header contained in the apache2handler section under the headline HTTP Headers Information as HTTP Response Headers. PHP seems to be able to access this info somehow.

I tried headers_list() and apache_response_headers() to get this information for my script, but it is missing.

A Google search did not come up with a solution, it seems like this to be a rare case. One other question here on SO got the answer to really query the server again and look at the headers, but I won’t do this because I need the info on every request I serve – subrequests seem to be too much of a performance penalty.

How does phpinfo() know the values?

Update1: PHP does not show the value inside any of the superglobals like $_SERVER, $_ENV etc. The only place I see it on the phpinfo page is in the above mentioned section. Otherwise this would be a no-brainer.

Answers:

You could do this, but make sure it’s higher in the file than anything else that prints or you will get an error.

<?php
foreach($_SERVER as $h=>$v)
 if(preg_match('/HTTP_(.+)/',$h,$hp))
   echo "<li>$h = $v</li>\n";
?>

Edit:
Do you have FastCGI enabled?

Try this link: $_SERVER headers are missing in PHP but present in Python

Leave a Reply

Your email address will not be published. Required fields are marked *