Select the type of mobile device

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:
Mozilla/5.0+(iPhone;+U;+CPU+iPhone+OS+4_3_2+like+Mac+OS+X;+en-us)+AppleWebKit/533.17.9+(KHTML,+like+Gecko )+Version/5.0.2+Mobile/8H7+Safari/6533.18.5
Here’s the user agent for an iPad:
Mozilla/5.0+(iPad;+U;+CPU+OS+4_3_2+like+Mac+OS+X;+en-us) +AppleWebKit/533.17.9+(KHTML,+like+Gecko)+Version/5.0.2+Mobile/8H7+Safari/6533.18.5
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.)
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.

Leave a Comment