[ Team LiB ] Previous Section Next Section

The $_SERVER Array

The $_SERVER array contains elements set by your script's context, usually the server. There is no guarantee that any or all of the common elements will be set in it. If you are running PHP as a server module, however, it is likely that you will find at least the elements summarized in Table 10.2. They can be very useful in providing additional information about the context of a user request.

In Listing 10.1, we loop through the $_SERVER array, printing the results to the browser.

Listing 10.1 Looping Through the $_SERVER Array
 1: <!DOCTYPE html PUBLIC
 2:     "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 10.1 Looping through the $_SERVER array</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: foreach ( $_SERVER as $key=>$value ) {
12:    print "\$_SERVER[\"$key\"] == $value<br/>";
13: }
14: ?>
15: </div>
16: </body>
17: </html>

We use a foreach loop to access the keys and values in $_SERVER, printing to the browser on line 12. If PHP is running as a server module, you should find the elements listed in Table 10.2 in the output.

Table 10.2. Some Common $_SERVER Elements

Variable

Contains

Example

$_SERVER['PHP_SELF']

The current script. Suitable for use in links and form element action arguments.

/phpbook/source/listing10.1.php

$_SERVER['HTTP_USER_AGENT']

The name and version of the client.

Mozilla/4.6 –(X11; I;Linux2.2. 6-15apmac ppc)

$_SERVER['REMOTE_ADDR']

The IP address of the client.

158.152.55.35

$_SERVER['REQUEST_METHOD']

Whether the request was GET or POST.

POST

$_SERVER['QUERY_STRING']

For GET requests, the encoded data sent appended to the URL.

name=matt&address=unknown

$_SERVER['REQUEST_URI']

The full address of the request, including query string.

/phpbook/source/listing10.1.php? name=matt

$_SERVER['HTTP_REFERER']

The address of the page from which the request was made.

http://p24.corrosive.co.uk/ref.html

Note the PHP_SELF element in particular. We use it to point forms and links back at their enclosing scripts in examples throughout this book.

    [ Team LiB ] Previous Section Next Section