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:

<?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

Using apache_request_headers() Function

Now, let’s check out an example of using another helpful method that is the 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 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.