How can I get PHP to display the headers it received from a browser?

PHP provides several methods to display HTTP headers received from a browser. You can access individual headers through the $_SERVER superglobal or retrieve all headers using the getallheaders() function.

Using $_SERVER Superglobal

To access a specific header, use the $_SERVER array with the header name prefixed by HTTP_ ?

<?php 
echo $_SERVER['HTTP_HOST'];
echo $_SERVER['HTTP_USER_AGENT'];
?>

Using getallheaders() Function

The getallheaders() function returns all HTTP request headers as an associative array ?

<?php
$headers = getallheaders();
foreach($headers as $key => $val){
    echo $key . ': ' . $val . '<br>';
}
?>

Alternative Method Using $_SERVER

You can also extract all HTTP headers by filtering the $_SERVER array ?

<?php
foreach($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $header = str_replace('HTTP_', '', $key);
        $header = str_replace('_', '-', $header);
        echo ucwords(strtolower($header), '-') . ': ' . $value . '<br>';
    }
}
?>

Output

The methods above will produce output similar to the following ?

Host: www.websitename.com
Content-Length: 180
Cache-Control: max-age=0
Origin: http://www.websitename.com
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://www.writephponline.com/
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Cookie: _ga=GA1.2.118418268.1575911248; _gid=GA1.2.1794052867.1576852059
Note: The getallheaders() function requires a web server environment and may not be available in all PHP installations. The $_SERVER method is more universally compatible.

Conclusion

Use getallheaders() for simple header retrieval or $_SERVER for better compatibility. Both methods provide access to HTTP headers sent by the browser to your PHP script.

Updated on: 2026-03-15T08:41:39+05:30

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements