Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read any request header in PHP

How should I read any header in PHP?

For example the custom header: X-Requested-With.

like image 322
Sabya Avatar asked Feb 12 '09 14:02

Sabya


People also ask

How do I view headers in PHP?

The get_headers() function in PHP is used to fetch all the headers sent by the server in the response of an HTTP request.

How do I read request headers?

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.

How do headers work in PHP?

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).


1 Answers

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.

like image 74
Jacco Avatar answered Sep 18 '22 18:09

Jacco