Home and Learn: PHP Programming Course

PHP Server Variables


PHP stores a list of information about the server. This will include things like, the browser the visitor is using, the IP address, and which web page the visitor came from. Here's a script to try with those three Server Variables:

$referrer = $_SERVER['HTTP_REFERER'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$ipAddress = $_SERVER['REMOTE_ADDR'];

print "Referrer = " . $referrer . "<BR>";
print "Browser = " . $browser . "<BR>";
print "IP Adress = " . $ipAddress;

These are useful if you want to log your stats, or to ban a particular IP address! (If you run the script on a local machine, you may get an error for the referrer.)

So to get at the values in Server Variables, the syntax is this:


You start with a dollar sign, then an underscore character ( $_ ). Then you add the word SERVER. In between square brackets, you type the name of the server variable you want to access. Surround this with either single or double quotes.

Because you are returning a value, you need to put all that on the right hand side of an equals sign. On the left of the equals sign ( = ), you need a variable to hold the string that is returned.

The server variables are held in an array (associative), so you can use a foreach loop to get a list of all available ones. Try this script:


foreach($_SERVER as $key_name => $key_value) {

print $key_name . " = " . $key_value . "<br>";



What the script does is to loop round all the server variables and print out the keys and values in the SERVER array.

<-- Back One Page | Move on to the Next Part -->

Back to the PHP Contents Page


Email us: enquiry at homeandlearn.co.uk