Get HTTP Headers Using PHP

Fri 03 October 2014
By alex

The getenv() function is used to parse enviroment variables created by the webserver executing the php code, including HTTP Headers.

<?php
$client_ip = getenv('REMOTE_ADDR');
$user_agent = getenv('HTTP_USER_AGENT');

echo "Client IP: $client_ip</br>"
echo "User Agent: $user_agent</br>"
?>

Using conditional statements, the headers can be parsed and then actions taken based upon their contents.

<?php
$ua = getenv('HTTP_USER_AGENT');

if (strpos($ua, 'Wget') !== false) {
    http_response_code(403);
    echo "Don't wget me";
}
?>

apache_request_headers() returns an associative array containing all the headers passed to the server in a request. This provides access to headers outside of what apache exposes.

<?php
$headers = apache_request_headers();

if ($headers['x-forwarded-for']) {
    http_response_code(403);
    echo "No proxies jackhole";
}
?>

To see the values of all of apache's environment variables as well as all request headers, upload this script to your apache instance