Information Technology Reference
In-Depth Information
PHP User Agent Detection
Listing 6-1 shows a PHP example in which we are going to detect the user agent string
and display it to the user. If the user is using an Android web browser, then they will be
presented with the always pleasant smiley face (see Figure 6-3), but if they try viewing
the script on a non-Android powered device, then they will be accosted with the ever
unpopular frowny face (see Figure 6-4).
Listing 6-1. PHP User Detection Code
<?php
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($userAgent,'android') !== false) {
echo 'You are using an Android web browser! :)';
}
else {
echo 'You are not using an Android web browser! :(';
}
?>
To understand how this code is working, we are going to pick it apart, line by line. First,
we define the variable $userAgent, which grabs the user agent string of the browser
requesting the page. Then we use the PHP stripos function—which searches a string for
the occurrence of a string—to parse the user agent for our supplied value. If the value, in
this case android, is not found within the string, then the user is presented one
message. If it is found, another message is presented.
This is just a small example of how you can use PHP to detect a user agent string, but
there are many more situations where this technique might save you from ripping your
own hair out. For example, using detection in PHP may allow you to block content
before it is even sent (something JavaScript detection won't do, generally). Also, if the
bulk of your application is written in PHP, you may be more comfortable recording user
agents in this manner, rather than through JavaScript.
Figure 6-3. Using PHP, we are taking the user agent string and using that to decide which content is showed to
the end user
 
Search WWH ::




Custom Search