How should I read any header in PHP?
For example the custom header: X-Requested-With
.
The get_headers() function in PHP is used to fetch all the headers sent by the server in the response of an HTTP request.
Reading Request Headers from Servlets Reading headers is very straightforward; just call the getHeader method of the HttpServletRequest , which returns a String if the header was supplied on this request, null otherwise.
The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request).
IF: you only need a single header, instead of all headers, the quickest method is:
<?php // Replace XXXXXX_XXXX with the name of the header you need in UPPERCASE (and with '-' replaced by '_') $headerStringValue = $_SERVER['HTTP_XXXXXX_XXXX'];
ELSE IF: you run PHP as an Apache module or, as of PHP 5.4, using FastCGI (simple method):
apache_request_headers()
<?php $headers = apache_request_headers(); foreach ($headers as $header => $value) { echo "$header: $value <br />\n"; }
ELSE: In any other case, you can use (userland implementation):
<?php function getRequestHeaders() { $headers = array(); foreach($_SERVER as $key => $value) { if (substr($key, 0, 5) <> 'HTTP_') { continue; } $header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5))))); $headers[$header] = $value; } return $headers; } $headers = getRequestHeaders(); foreach ($headers as $header => $value) { echo "$header: $value <br />\n"; }
See Also:
getallheaders() - (PHP >= 5.4) cross platform edition Alias of apache_request_headers()
apache_response_headers() - Fetch all HTTP response headers.
headers_list() - Fetch a list of headers to be sent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With