How to read any request header in PHP

HTTP Header: HTTP headers are the code that transfers the data between web server and browser. The HTTP headers are mainly intended for the communication between the server and the client in both directions.

HTTP Request Header: When type a URL in the address bar of browser and try to access it, the browser sends an HTTP request to the server. The HTTP request header contains information in a text-record form, which includes many useful informations such as the type, capabilities, and version of the browser that generates the request, the operating system used by the client, the page that was requested, the various types of outputs accepted by the browser, and so on. Receiving the request header, the web server will send an HTTP response header back to the client.

Read any request header: It can be achieved by using getallheaders() function.



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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 

Example 2: It can be achieved by using apache_request_headers() function.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
$header = apache_request_headers();
  
foreach ($header as $headers => $value) {
    echo "$headers: $value <br />\n";
}
?>

chevron_right


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 

Reference: http://php.net/manual/en/function.header.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.