As we start building up dynamic web pages with PHP we perhaps need to be able to test for the browser type in our pages, in any case, this is a great start to using variables and conditional statements within PHP pages. First we can use super globals to display the browser type.
<?php $user_agent = $_SERVER['HTTP_USER_AGENT']; echo "$user_agent . <br>"; ?>
We are accessing the super global here, $_SERVER, this is an array and we access the key HTTP_USER_AGENT. If we want to list the complete list of keys in $_SERVER we could use the function print_r:
<?php
echo “<pre>”;
print_r($_SERVER);
echo “</pre>”;
?>
Really though, we don’t just want to print information; lets add in some conditional statements to run different code for different browsers:
<?php $user_agent = $_SERVER['HTTP_USER_AGENT'] . "<br>"; if (strpos($user_agent, 'Mozilla') !==false) { echo "Nice one <br>"; } else { echo "Never mind <br>"; } ?>
Using this code we test using the function strpos for Mozilla being present in the HTTP_USER_AGENT string. On Firefox we can see the postive affirmation:
As a starting point in learning PHP this makes a great start, soon we will be looking at how we can access LDAP directories and MySQL databases with code and formatting the pages with CSS.