In Part 1 of this series, we set up a basic PHP server with Apache on a Red Hat system, and wrote a simple “Hello World” script. In this article, we will vary content based on browser type.
We will use the HTTP_SERVER_VARS server variable. The specific variable we want is HTTP_SERVER_VARS[‘HTTP_USER_AGENT’]. To use this, let’s create a small HTML/PHP doc that echoes back the variable:
[root@srv-33 website]# cat index.php <html> <head> <title>HTTP_SERVER_VARS_USER_AGENT</title> </head> <body> <?php echo $HTTP_SERVER_VARS['HTTP_USER_AGENT']; ?> </body> </html> [root@srv-33 website]# |
Notice how you can put normal HTML in a .php document. Just put the <?php and ?> tags around the PHP part.
Let’s vary our content based on the platform the browser is running on. If the platform is Linux, then we will put a nice penguin graphic on the page. If not, we will say “You could have had a penguin!!.
Now, we are Perl fans, so we prefer the perl-style regular expressions. The preg_match does just that. For more info, look here. The i means to ignore case. Now, we have never seen a Linux user agent string that didn’t have a capital L, but it is probably wise to ignore case anyway. We don’t want to offend possible Linux users that want to see the penguin, and can’t, because their user agent string has a lower case l. 🙂 Of course, the string the browser passes can’t really be relied on, but in most cases this should work from our experience glancing at http logs. The final html looks like this:
[root@srv-33 website]# cat index.php <html> <head> <title>HTTP_SERVER_VARS_USER_AGENT</title> </head> <body> <?php $hv=$HTTP_SERVER_VARS['HTTP_USER_AGENT']; if(preg_match ("/linux/i",$hv)){ echo "<img src=\"tux.png\">"; } else { echo "You could have had a penguin!!!"; } ?> </body> </html> [root@srv-33 website]# |