Php read html headers

How do I read any request header in PHP

«Any header» is ambiguous. You can’t read «any header» in one operation, but you can read the incoming list of request headers and the current outgoing list of response headers separately.

16 Answers 16

IF: you only need a single header, instead of all headers, the quickest method is:

ELSE IF: you run PHP as an Apache module or, as of PHP 5.4, using FastCGI (simple method):

ELSE: In any other case, you can use (userland implementation):

 $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 
\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.

I don’t care about 82% of amateurs. I care about professional installations. No one in right state of mind would try to run high traffic site on mod_php.

@Jacco Yes, and I think that makes a perfect reason for downvoting. At any given time the best answer should be upvoted and bad answers downvoted. This is not a site of historical solutions 🙂

@ThomasJensen Consider though, that some might be interessted in other or all headers and not esspecially in ‘HTTP_X_REQUESTED_WITH’; The answere is absolute correct and Jacco explecitely stated that it only works for apache; That it in some scenarios not the best / most performant solution is no reason for a downvote IMO.

Читайте также:  Php return json post

@Paranaix A: I don’t know what you mean, I haven’t criticized the extent of the answer and your reasoning is exactly why I started my answer by answering the specific question and then elaborated with more general knowledge and links for further information. B: I still don’t think you should encourage the use of apache_request_headers(). Newbies finding this question will start using it which is a shame IMO when better functions exist.

$_SERVER['HTTP_X_REQUESTED_WITH'] 

Meta-variables with names beginning with HTTP_ contain values read from the client request header fields, if the protocol used is HTTP. The HTTP header field name is converted to upper case, has all occurrences of — replaced with _ and has HTTP_ prepended to give the meta-variable name.

Can I reliably expect any server to put every header into the $_SERVER variable? The PHP documentation at php.net/manual/en/reserved.variables.server.php is evasive about what we can be sure will be in there.

This will not (always) work, especially in PHP-fpm (or cgi ). This header is not always available from within PHP.

Using this solution I only see some of the request headers, and in this case, i don’t see the one I want. Chrome is sending a cache-control header, but I do not see it anywhere in $_SERVER . I do see several headers prefixed with HTTP_ , including «HTTP_ACCEPT», and «HTTP_UPGRADE_INSECURE_REQUESTS» and «HTTP_USER_AGENT» (among several others). But nothing for «cache-control» also nothing for «pragma». This is regardless of case or HTTP_ prefix. Am I missing something?

hmmm, thanks. This is on my wamp dev server and I think PHP is running as an Apache module but I’m not sure. Let me check on my prod box with FPM and see if I can figure out why I don’t see it here on wamp.

You should find all HTTP headers in the $_SERVER global variable prefixed with HTTP_ uppercased and with dashes (-) replaced by underscores (_).

For instance your X-Requested-With can be found in:

$_SERVER['HTTP_X_REQUESTED_WITH'] 

It might be convenient to create an associative array from the $_SERVER variable. This can be done in several styles, but here’s a function that outputs camelcased keys:

$headers = array(); foreach ($_SERVER as $key => $value) < if (strpos($key, 'HTTP_') === 0) < $headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value; >> 

Now just use $headers[‘XRequestedWith’] to retrieve the desired header.

The best answer, in my opinion, is Thomas’s explanation with Quassnoi’s end result. An associative array is usually not what’s needed, and it isn’t very easy to work out the simple solution from reading the parseRequestHeaders() function. If such an associative array is needed, then IMO the apache function is the best option, since it returns exactly the headers received instead of a mangled CamelCase version. (Also note that as of PHP 5.4, it is no longer Apache-only.)

apache_request_headers() or getallheaders() doesn’t seem to capitalize the Header names when I tested. They are returning exactly as I pass from client side. Then why are you capitalizing header names in such a replacement function?

Since PHP 5.4.0 you can use getallheaders function which returns all request headers as an associative array:

var_dump(getallheaders()); // array(8) < // ["Accept"]=>// string(63) "text/html[. ]" // ["Accept-Charset"]=> // string(31) "ISSO-8859-1[. ]" // ["Accept-Encoding"]=> // string(17) "gzip,deflate,sdch" // ["Accept-Language"]=> // string(14) "en-US,en;q=0.8" // ["Cache-Control"]=> // string(9) "max-age=0" // ["Connection"]=> // string(10) "keep-alive" // ["Host"]=> // string(9) "localhost" // ["User-Agent"]=> // string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) [. ]" // > 

Earlier this function worked only when PHP was running as an Apache/NSAPI module.

Pass a header name to this function to get its value without using for loop. Returns null if header not found.

/** * @var string $headerName case insensitive header name * * @return string|null header value or null if not found */ function get_header($headerName)

Note: this function will process and load all of the headers to the memory and it’s less performant than a for loop.

I was using CodeIgniter and used the code below to get it. May be useful for someone in future.

$this->input->get_request_header('X-Requested-With'); 

It was. Knew about get_request_header() method though, but wasn’t sure I could use the header name as is, i.e. without having to change hyphens to underscores.

strtolower is lacking in several of the proposed solutions, RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. The whole thing, not just the value part.

So suggestions like only parsing HTTP_ entries are wrong.

Better would be like this:

if (!function_exists('getallheaders')) < foreach ($_SERVER as $name =>$value) < /* RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. */ if (strtolower(substr($name, 0, 5)) == 'http_') < $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; >> $this->request_headers = $headers; > else < $this->request_headers = getallheaders(); > 

Notice the subtle differences with previous suggestions. The function here also works on php-fpm (+nginx).

Where exactly does RFC 2616 state that field values are case-insensitive? It explitly states that «HTTP-date is case sensitive» — and that goes into Date header — and that «Parameter values [text in Content-Type after semicolon] might or might not be case-sensitive». So given there are at least two headers with case-sensitive values, it seems that you’re wrong.

HTTP header fields, which include general-header (section 4.5), request-header (section 5.3), response-header (section 6.2), and entity-header (section 7.1) fields, follow the same generic format as that given in Section 3.1 of RFC 822 [9]. Each header field consists of a name followed by a colon («:») and the field value. Field names are case-insensitive. So I guess you’re wrong.

Field names are case-insensitive. There is nothing about field values in this paragraph, while other parts of the document explicitly tell about case-sensitive field values.

Why ya all replacing underline to space then space to dash? wouldn’t this just work: $headers[ucwords(strtolower(substr($name, 5)))] = $value; ?

if only one key is required to retrieved, For example «Host» address is required, then we can use

apache_request_headers()['Host'] 

So that we can avoid loops and put it inline to the echo outputs

you run PHP as an Apache module or, as of PHP 5.4, using FastCGI (simple method): apache_request_headers() as mentioned below

To make things simple, here is how you can get just the one you want:

$headerValue = $_SERVER['HTTP_X_REQUESTED_WITH']; 

or when you need to get one at a time:

 return $headerValue; > // X-Requested-With mainly used to identify Ajax requests. Most JavaScript frameworks // send this header with value of XMLHttpRequest, so this will not always be present. $header_x_requested_with = get_header( 'X-Requested-With' ); 

The other headers are also in the super global array $_SERVER, you can read about how to get at them here: http://php.net/manual/en/reserved.variables.server.php

Comparing to other answers it seems that you function will not work as it does not prepend HTTP_ to the $headerKey

Here’s how I’m doing it. You need to get all headers if $header_name isn’t passed:

 else < $header_name_safe=str_replace("-", "_", strtoupper(preg_quote($header_name))); $headers=preg_grep("/^HTTP_$$/si", $keys); > foreach($headers as $header) < if(is_null($header_name))< $headervals[substr($header, 5)]=$_SERVER[$header]; >else < return $_SERVER[$header]; >> return $headervals; > print_r(getHeaders()); echo "\n\n".getHeaders("Accept-Language"); ?> 

It looks a lot simpler to me than most of the examples given in other answers. This also gets the method (GET/POST/etc.) and the URI requested when getting all of the headers which can be useful if you’re trying to use it in logging.

Array ( [HOST] => 127.0.0.1 [USER_AGENT] => Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0 [ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [ACCEPT_LANGUAGE] => en-US,en;q=0.5 [ACCEPT_ENCODING] => gzip, deflate [COOKIE] => PHPSESSID=MySessionCookieHere [CONNECTION] => keep-alive ) en-US,en;q=0.5 

Источник

How to Read Request Headers in PHP

When typing a URL in the browser’s address bar and trying to access it, an HTTP request is sent to the server by the browser. It encompasses information in a text-record state including the type, the capabilities, user’s operation system, the browser generating the request, and more.

Getting the request header, the web server sends an HTTP response head to the client.

Below, we will show you how to read any request header in PHP.

Using the getallheaders() Function

To achieve what was described above, you can use the getllheaders() function.

Let’s check out an example with its output:

 foreach (getallheaders() as $name => $value) < echo "$name: $value 
"
; > ?>
Host: 127.0.0.3:2025 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36 Accept: text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, image/apng, */*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-US, en;q=0.9

Using apache_request_headers() Function

Now, let’s check out an example of using another helpful method that is the apache_request_headers() function:

 $header = apache_request_headers(); foreach ($header as $headers => $value) < echo "$headers: $value 
\n"
; > ?>

The output will look as follows:

Host: 127.0.0.6:2027 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36 Accept: text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, image/apng, */*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-US, en;q=0.9

Describing HTTP Headers

An HTTP header is considered a code, which transfers the data between the browser and the web server.

Generally, HTTP headers are used for the communication between the client and the server in both of the directions.

Источник

How can I get PHP to display the headers it received from a browser?

you can use getallheaders() to get an array of all HTTP headers sent.

$headers = getallheaders(); foreach($headers as $key=>$val)< echo $key . ': ' . $val . '
'; >

Every HTTP request header field is in $_SERVER (except Cookie ) and the key begins with HTTP_ . If you’re using Apache, you can also try apache_request_headers .

@dskanth Yes, $_COOKIE will contain the already parsed cookies sent by the client. But there won’t be a $_SERVER[‘HTTP_COOKIE’] .

@Gumbo, How is this diff from getallheaders ? Are there some headers that are stripped for the latter?

@Pacerier getallheaders is part of a server specific extension, thus it might be available only when using Apache module. On the other hand $_SERVER is always available (working as web-server).

Usage: echo json_encode(getallheaders());

If above function does not exist (old PHP or nginx) you can use this as a fallback:

Look at the $_SERVER variable to see what it contains. The linked manual page has a lot of useful information, but also simply do a var_dump on it to see what’s actually in it. Many of the entries will or won’t be filled in, depending on what the client decides to do, and odd quirks of PHP. Looking at the one on my local server, there is also a $_SERVER[«ALL_HTTP»] entries that just lists them all as a string, but apparently this isn’t standard, as it isn’t listed on the manual page.

you can use apache_request_header(); maybe help you.

$headers = apache_request_headers(); foreach ($headers as $header => $value) < echo "
"; echo "$header : $value"; echo "

"; >

Источник

Оцените статью