Determine the Mobile Device Type
In the contact page example, and in the following code sample, you see how to check the user agent for key terms that indicate which type of browser is being used to visit your site. The user agent, which is sent with the request from a browser to a web server, is a text description that identifies the browser version and operating system.
Here’s the current user agent for an iPhone:
Here’s the user agent for an iPad:
You insert the following code into your web page to detect the user agent and deliver the optimized version of the page to each device. (Note that the line numbers on the right aren’t a required part of the code. They’re included only for your reference as we examine a few lines of code in detail in the next paragraph.)
<?php 1 $ua = $_SERVER['HTTP_USER_AGENT']; 2 $iPhone = strpos($ua,"iPhone"); 3 $iPad = strpos($ua,"iPad"); 4 $iPod = strpos($ua,"iPod"); 5 $Mac = strpos($ua,"Mac OS X"); 6 ?>
The following list explains what’s happening in the preceding code block:
Line 1: Tells the web server to process the following as PHP code before sending the page to the browser.
Line 2: Retrieves the user agent from the browser’s request for this page. You create a variable named $ua and assign it the value of $_SERVER[‘HTTP_USER_AGENT’. Now the variable ($ua) has the value of the user agent string. If an iPhone visited the site, $ua would have the value of the iPhone user agent.
Line 3: Creates a variable named $iPhone. Then using the function strpos(), PHP finds the position of “iPhone” in $ua and assigns its starting position to $iPhone.
$iPhone = strpos($ua,"iPhone");
If $ua doesn’t contain “iPhone” strpos() returns FALSE. Later in the page, you can recognize whether a iPhone is requesting a page by testing the value of $iPhone.
Lines 4, 5, 6: Detect other systems in the same way as Line 3.