3 Quick Ways to Read PHP Request Headers

read PHP request headers
Image by Sumanley xulx from Pixabay

Sometimes we may require reading PHP request headers sent from the user client at the server side in PHP. This includes but not limited to checking which browser-client user is using, what is the IP address from where the hit is initiated etc.

There are 3 ways in which you can read HTTP header values that are sent from the browser.

PHP get_headers() Function

get_headers() function is used to read all the headers sent by the server in response to an HTTP request. The syntax of PHP get_headers() is:

get_headers( $url, $format, $context )

$url – This is the mandatory parameter that defines the target URL. It is of type string.
$format –  It is an optional parameter of type int. If its value is set to non-zero it will return an associative array otherwise indexed array.
$context – It holds the valid resource context created by stream_context_create() function.

Let’s see its example:

<?php
  
// Target URL
$url = "https://codetopology.com";
  
// Reading headers
$headers = get_headers($url);
  
// Printing headers
print_r($headers);
?>

When you hit the above code from the browser, it will return:

Array ( [0] => HTTP/1.1 200 OK [1] => Date: Sun, 24 Jul 2022 13:03:00 GMT [2] => Content-Type: text/html; charset=UTF-8 [3] => Connection: close [4] => x-powered-by: PHP/7.4.30 [5] => last-modified: Sun, 24 Jul 2022 13:03:00 GMT [6] => vary: Accept-Encoding [7] => content-security-policy: upgrade-insecure-requests [8] => referrer-policy: no-referrer-when-downgrade [9] => x-turbo-charged-by: LiteSpeed [10] => CF-Cache-Status: DYNAMIC [11] => Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" [12] => Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=41s8A6zJNLtceDdy0oFkH5jQMmC3T1MlhNDdY18LoUtFKDfnGI8vn2xCMDnZwfylTtLy4icmOCckIJvwxYxEHWJ7v8u0Q2OziFlJw1Sovx6%2BmkBqxdqxUrLXVtzsVvHegDxA"}],"group":"cf-nel","max_age":604800} [13] => NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800} [14] => Server: cloudflare [15] => CF-RAY: 72fcda7b8b2d8879-LHR [16] => alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400 )

$_SERVER superglobal variable

$_SERVER is a PHP super global variable that holds essential information about headers, paths, and script locations. This is the associative array and most of the values are populated by the server on which this variable is used.

Let’s see what data does $_SERVER variable holds:

CodeDescription
$_SERVER[‘PHP_SELF’]Returns the filename of the currently executing script
$_SERVER[‘SERVER_ADDR’]Returns the IP address of the host server
$_SERVER[‘SERVER_NAME’]Returns the name of the host server (such as www.w3schools.com)
$_SERVER[‘SERVER_SOFTWARE’]Returns the server identification string (such as Apache/2.2.24)
$_SERVER[‘SERVER_PROTOCOL’]Returns the name and revision of the information protocol (such as HTTP/1.1)
$_SERVER[‘REQUEST_METHOD’]Returns the request method used to access the page (such as POST)
$_SERVER[‘REQUEST_TIME’]Returns the timestamp of the start of the request (such as 1377687496)
$_SERVER[‘QUERY_STRING’]Returns the query string if the page is accessed via a query string
$_SERVER[‘HTTP_ACCEPT’]Returns the Accept header from the current request
$_SERVER[‘HTTP_HOST’]Returns the Host header from the current request
$_SERVER[‘HTTP_REFERER’]Returns the complete URL of the current page (not reliable because not all user agents support it)
$_SERVER[‘HTTPS’]Is the script queried through a secure HTTP protocol
$_SERVER[‘REMOTE_ADDR’]Returns the IP address from where the user is viewing the current page
$_SERVER[‘REMOTE_HOST’]Returns the Hostname from where the user is viewing the current page
$_SERVER[‘REMOTE_PORT’]Returns the port being used on the user’s machine to communicate with the web server
$_SERVER[‘SCRIPT_FILENAME’]Returns the absolute pathname of the currently executing script
$_SERVER[‘SERVER_ADMIN’]Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on a virtual host, it will be the value defined for that virtual host) (such as [email protected])
$_SERVER[‘SERVER_PORT’]Returns the port on the server machine being used by the web server for communication (such as 80)

As this is the array, you need to pass key name to $_SERVER array.

Let’s see its working example:

<?php

//Loop through SERVER values
foreach ($_SERVER as $k=>$v)
echo $k . "=>" . $v . "<br>";
?>

Output is :

USER=>www-data
HOME=>/var/www
SCRIPT_NAME=>/test.php
REQUEST_URI=>/test.php
QUERY_STRING=>
REQUEST_METHOD=>GET
SERVER_PROTOCOL=>HTTP/1.1
GATEWAY_INTERFACE=>CGI/1.1
REMOTE_PORT=>51226
SCRIPT_FILENAME=>/var/www/html/test.php
SERVER_ADMIN=>webmaster@localhost
CONTEXT_DOCUMENT_ROOT=>/var/www/html
CONTEXT_PREFIX=>
REQUEST_SCHEME=>http
DOCUMENT_ROOT=>/var/www/html
REMOTE_ADDR=>::1
SERVER_PORT=>80
SERVER_ADDR=>::1
SERVER_NAME=>localhost
SERVER_SOFTWARE=>Apache/2.4.41 (Ubuntu)
SERVER_SIGNATURE=>
Apache/2.4.41 (Ubuntu) Server at localhost Port 80

PATH=>/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
HTTP_COOKIE=>_ga=GA1.1.134870573.1639529311; _ga_16V2EP9YR6=GS1.1.1653592039.1.0.1653592048.0; _ga_XCXWG881JE=GS1.1.1657260357.4.1.1657260704.0
HTTP_ACCEPT_LANGUAGE=>en-GB,en-US;q=0.9,en;q=0.8
HTTP_ACCEPT_ENCODING=>gzip, deflate, br
HTTP_SEC_FETCH_DEST=>document
HTTP_SEC_FETCH_USER=>?1
HTTP_SEC_FETCH_MODE=>navigate
HTTP_SEC_FETCH_SITE=>none
HTTP_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
HTTP_USER_AGENT=>Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36
HTTP_UPGRADE_INSECURE_REQUESTS=>1
HTTP_SEC_CH_UA_PLATFORM=>"Linux"
HTTP_SEC_CH_UA_MOBILE=>?0
HTTP_SEC_CH_UA=>" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
HTTP_CACHE_CONTROL=>max-age=0
HTTP_CONNECTION=>keep-alive
HTTP_HOST=>localhost
proxy-nokeepalive=>1
HTTP_AUTHORIZATION=>
FCGI_ROLE=>RESPONDER
PHP_SELF=>/test.php
REQUEST_TIME_FLOAT=>1658668541.4387
REQUEST_TIME=>1658668541

apache_request_headers()

apache_request_headers() is the built-in PHP function. It fetched all HTTP request headers from the current request. It works in the Apache, FastCGI, CLI, and FPM webservers.

This function does not contain any parameters. It returns false if a request is failed.

<?php
$headers = apache_request_headers();

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

Output is:

Cookie: _ga=GA1.1.134870573.1639529311; _ga_16V2EP9YR6=GS1.1.1653592039.1.0.1653592048.0; _ga_XCXWG881JE=GS1.1.1657260357.4.1.1657260704.0
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Accept-Encoding: gzip, deflate, br
Sec-Fetch-Dest: document
Sec-Fetch-User: ?1
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
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
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36
Upgrade-Insecure-Requests: 1
Sec-Ch-Ua-Platform: "Linux"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
Cache-Control: max-age=0
Connection: keep-alive
Host: localhost
Authorization:

If you observe the $_SERVER output and apache_request_headers() output, you will see $_SERVER does not provide authorization information in output where as apache_request_headers provide the authorization info.

One thought

  1. I’ve been surfing online more than 3 hours these days,
    but I never found any fascinating article like yours.
    It is lovely value enough for me. Personally, if all site owners and bloggers made excellent content material as you probably did,
    the internet shall be much more helpful than ever
    before.

Leave a Reply

Your email address will not be published. Required fields are marked *