The University of Texas at Austin- What Starts Here Changes the World
Services Navigation

Example 3 - Conditionals

Now we will add some intelligence to Example 2 so it will display one message if the user is using Internet Explorer and another message if they are using Netscape. This is very useful when you need to create different pages for browser compatibility reasons.

<TITLE> Example 3 </TITLE>


print("Hello World<br>");
print("You are using $_SERVER[HTTP_USER_AGENT]<br>");
print("Your Internet address is $_SERVER[REMOTE_ADDR]<br>");
// check to see if the $_SERVER[HTTP_USER_AGENT] variable contains MSIE
// the string or Internet Explorer
// this uses the ereg function for regular expressions

      print("Go to to download the latest version");
    } else {
       print("Go to to download the latest version");




Example 3 adds several new constructs, regular expressions and conditionals. Let's address the conditional first. PHP is very similar to Perl, C, and Javascript in the way it handles conditions. The general syntax of a conditional is:

if (condition) {
   statement(s) to execute if condition is true;
} else {
   statement to execute if condition is false;

In our example the condition we want to test is whether the user is using any version of Internet Explorer. Most versions have the string "MSIE" in the $_SERVER[HTTP_USER_AGENT] variable so we need to determine if that variable contains "MSIE". PHP supports regular expressions using the ereg function. The syntax of the ereg() function is:

ereg(regular expression, string to match);

where regular expression is what you want to search for and string to match is where you want to search. This will return true if $_SERVER[HTTP_USER_AGENT] contains the MSIE string.

Regular expressions are very powerful tools. For purposes of these examples, it's probably best to think of regular expressions as search terms. PHP searches for the expression in the specified variable and returns a value of true if it finds the expression. In this, example users will be pointed to Microsoft's Web site if they are using Internet Explorer and to Netscape's web site if they are not.

Test Example 3

View Source Code

PHP Manual Pages


  Updated 2005 August 1
  Comments to