How can I read these Apache
HTTP Headers
using PHP
before they’re sent to the client’s browser?
HTTP/1.1 200 OK
Last-Modified: Sun, 09 Jul 2023 09:41:38 GMT
Expires: Mon, 10 Jul 2023 07:20:55 GMT
Cache-Control: private, max-age=0
Date: Mon, 10 Jul 2023 07:20:55 GMT
Content-Type: application/json; charset=UTF-8
Content-Length: 2561
2
Answers
You don’t have full control over this entire list, and different parts of your stack control these values. Some of these are only determined after your script is done (for example your webserver).
You can set many of them with
header()
. But the short answer is that there’s no one place where you can read these.It is only possible to read headers sent by PHP, not the ones created by Apache settings.
Raw PHP provides headers_list() and headers_sent() for inspection of headers sending to client.
headers_list()
will return a list of headers to be sent to the browser / client.headers_sent()
Checks if or where headers have been sent.However, I think the best practice nowadays is to use PHP frameworks that supports PSR-7‘s ResponseInterface as output instead of doing straightforward echo and header() calls.
If you’re using such framework, instead you’d create and accumulate the response object that implements
ResponseInterface
methods. You may then, at any point, simply use it’s getHeaders() method to get previously set output headers.Unless your needs are very trivial, I’d suggest using modern PHP frameworks for development.