PHP getallheaders(): Get All Headers

The PHP getallheaders() function is used when we need to fetch all HTTP request headers. For example:

<?php
   $headers = getallheaders();
   foreach ($headers as $key => $value)
   {
      echo "$key: $value";
      echo "<BR>";
   }
?>

The output of the above PHP example on the getallheaders() function is:

php getallheaders function

That is:

Host: localhost
Connection: keep-alive
Cache-Control: max-age=0
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: foo=bar

The above example can also be written in this way:

<?php
   foreach(getallheaders() as $key => $value)
      echo "<b>", $key, "</b>: ", $value, "<BR>";
?>

Now the output should be:

php getallheaders example

You can also show the information of all HTTP headers in the form of a table using the following PHP script:

<?php
   echo "<table><tr>";
   echo "<th>Name</th>";
   echo "<th>Value</th>";
   echo "</tr>";
   foreach(getallheaders() as $key => $value)
   {
      echo "<tr>";
      echo "<td>", $key, "</td>";
      echo "<td>", $value, "</td>";
      echo "</tr>";
   }
   echo "</table>";
?>

PHP getallheaders() syntax

The syntax of the getallheaders() function in PHP is:

getallheaders()

Advantages of the getallheaders() function in PHP

Disadvantages of the getallheaders() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!