W3docs

How to Read Request Headers in PHP

The given snippet explores how to read request readers in PHP. Read it and learn the most helpful methods of reading any request headers in PHP.

When you type a URL in the browser's address bar and press Enter, the browser sends an HTTP request to the server. This request includes metadata such as the browser type, capabilities, the user's operating system, and more.

The web server responds with an HTTP response that includes headers.

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 <kbd class="highlighted">getallheaders()</kbd> function.

Let’s check out an example with its output:

php use getallheaders()

<?php

foreach (getallheaders() as $name => $value) {
  echo "$name: $value <br>";
}

?>

The output is as follows:


  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

Note: getallheaders() and apache_request_headers() are Apache-specific. For PHP-FPM or CGI environments, use the $_SERVER superglobal instead (e.g., $_SERVER['HTTP_HOST']).

Using apache_request_headers() Function

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

using apache_request_headers() function

<?php

$header = apache_request_headers();

foreach ($header as $headers => $value) {
  echo "$headers: $value <br />\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 a metadata field that transfers information between the browser and the web server.

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