Something Useful
Let us do something more useful now.
We are going to check what sort of browser the visitor is
using. For that, we check the user agent string the browser
sends as part of the HTTP request. This information is stored
in a variable. Variables always start with a dollar-sign
in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT'].
Note: $_SERVER is a special reserved PHP variable that
contains all web server information. It is known as an autoglobal
(or superglobal). See the related manual page on superglobals
for more information. These special variables were introduced
in PHP 4.1.0. Before this time, we used the older $HTTP_*_VARS
arrays instead, such as $HTTP_SERVER_VARS. Although deprecated,
these older variables still exist. (See also the note on
old code.)
To display this variable, you can simply do:
Example 2-2. Printing a variable (Array element)
<?php echo $_SERVER['HTTP_USER_AGENT']; ?>
A sample output of this script may be:
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
There are many types of variables available in PHP. In the
above example we printed an Array element. Arrays can be
very useful.
$_SERVER is just one variable that PHP automatically makes
available to you. A list can be seen in the Reserved Variables
section of the manual or you can get a complete list of
them by creating a file that looks like this:
Example 2-3. Show all predefined variables with
phpinfo()
<?php phpinfo(); ?>
When you load up this file in your browser, you will see
a page full of information about PHP along with a list of
all the variables available to you.
You can put multiple PHP statements inside a PHP tag and
create little blocks of code that do more than just a single
echo. For example, if you want to check for Internet Explorer
you can do this:
|