Detecting Mobile Devices Using PHP
Updated November 2008 with Android support.
Don't you wish there were an easy way to detect whether your web site visitor is connecting with a desktop PC or a mobile device of some sort?
The good news is that using PHP (or another server-based scripting language), it's sort of easy to detect some devices by parsing the UserAgent string. Because the code is run on the server rather than in the browser itself (such as JavaScript), these PHP-based techniques yield better reliability in detecting mobile devices. Just remember that there are lots of important caveats, including:
- These technqniques depend on the contents of the UserAgent string. As a result, these techniques may not work if the browser is emulating a different one (e.g., some mobile browsers can be set to emulate Internet Explorer).
- Mobile operators can also change the UserAgent contents when the device is customized for their networks and added to their stock device portfolio. Operators also sometimes change the UserAgent value as the page request passes through their networks.
- UserAgent strings are moving targets. Once implemented, you'll need to monitor the effectiveness of your code against the list of your high priority devices or platforms.
Alternatives
The PHP code in this article is great if you're only concerned about the class of device (e.g., smartphone or not), or the mobile platform (e.g., iPhone or Symbian S60). If you need detailed device information or usage metrics, you may wish to check out HandsetDetection.com or WURFL (see below for more info).
Introducing the "uagent_info" Class
I created a PHP class called "uagent_info" to encapsulate the logic for detecting mobile devices. This class is easy to use and its API is highly modularized so that you can detect broad classes of devices (such as smartphones or WAP/WMP-capable devices), specific platforms (such as the iPhone/iPod Touch, Symbian S60 or BlackBerry).
Here is a sample block of the code so you can see how it is organized:
//************************** // The uagent_info class encapsulates information about // a browser's connection to your web site. // The object's methods return 1 for true, or 0 for false. class uagent_info { //Stores some info about the browser and device. var $useragent = ""; //Stores info about what content formats the browser can display. var $httpaccept = ""; // Standardized (and configurable) values for true and false. var $true = 1; var $false = 0; // A long list of strings which provide clues // about devices and capabilities. var $deviceIphone = 'iphone'; var $deviceIpod = 'ipod'; // [ SNIP! Other variables snipped out ] //************************** //The constructor. Initializes several default variables. function uagent_info() { $this->useragent = strtolower($_SERVER['HTTP_USER_AGENT']); $this->httpaccept = strtolower($_SERVER['HTTP_ACCEPT']); } //************************** //Returns the contents of the User Agent value, in lower case. function Get_Uagent() { return $this->useragent; } //************************** // Detects if the current device is an iPhone. function DetectIphone() { if (stripos($this->useragent, $this->deviceIphone) > -1) { //The iPod touch says it's an iPhone! So let's disambiguate. if ($this->DetectIpod() == $this->true) { return $this->false; } else return $this->true; } else return $this->false; } // [ SNIP! Other functions snipped out ] }
Using the "uagent_info" Class
First, instantiate the uagent_info object, then call one of its functions. The device detection functions return 1 for true or 0 for false. It's as simple as that! Here's an example:
//Instantiate the object to do our testing with. $uagent_obj = new uagent_info(); //Let's detect an iPhone. //This will return a 1 for true or 0 for false. $iPhone = $uagent_obj->DetectIphone(); //Do some logic with it now, such as print it. print(" You're using an iPhone: ".$iPhone."
"); //You might also want to print out the user agent string. $agent = $uagent_obj->Get_Uagent(); print("Your user agent string:
");
".$agent."
Let's put the PHP code through its paces below!
Detect iPhone & iPod Touch
Use the following code to detect whether the device viewing the page is an iPhone and/or iPod Touch. And don't forget: iPod Touches are devices, too!
Why detect this browser? Mobile Safari is based on WebKit and can render most desktop-targeted web content very well (generally excluding heavy AJAX pages). Don't send users to barebones WAP/WML pages! Instead, give iPhone users regular desktop pages, iPhone-optimized content or nicely formatted mobile-optimized content.
- You're using an iPhone: false
- You're using an iPod Touch: false
- You're using an iPhone: false
// Detects if the current device is an iPhone. $uagent_obj->DetectIphone(); // Detects if the current device is an iPod Touch. $uagent_obj->DetectIpod(); // Detects if the current device is an iPhone or iPod Touch. $uagent_obj->DetectIphoneOrIpod());
Detect Symbian S60 Smartphones
The most popular smartphone platform in the world is Symbian S60. Used primarily by Nokia and a few other manufacturers, S60 features an extremely capable browser.
Why detect this browser? Users with S60 phones as a group are the largest consumers of the mobile web. Similar to the iPhone, the S60 Open Source Browser is based on WebKit and can render most desktop-targeted web content very well (generally excluding heavy AJAX pages). Don't send users to barebones WAP/WML pages! Instead, give S60 users regular desktop pages or nicely formatted mobile-optimized content.
- You're using the WebKit browser on an S60 device: false
- You're using any Symbian OS-based device, including older S60, UIQ devices (loaded with Opera by default), or the S60 WAP browser: false
// Detects if the current browser is the Nokia S60 Open Source Browser. $uagent_obj->DetectS60OssBrowser(); // Detects if the current device is any Symbian OS-based device, // including older S60, Series 70, Series 80, Series 90, and UIQ, // or other browsers running on these devices. $uagent_obj->DetectSymbianOS();
Detect Android Devices
Besides the iPhone, the only other mobile device in recent times to receive as much attention, both from geeky fanboys and the general public, has been the T-Mobile G1, often called the "Google Phone." The G1 is powered by a new mobile phone operating system called Android, which Google has sponsored. Android is a smartphone-class OS with an advanced browser that is similar to Mobile Safari on the iPhone in capabilities.
We added two new methods to the PHP code to detect for Android phones. The first detects simply whether the device is running the Android OS. The second detects whether the browser is based on WebKit (like Mobile Safari). The second method may become important in the future as other web browser companies start to release browsers for Android.
Why detect this browser? The native Android browser is extremely capable and also based on WebKit, which underlies Mobile Safari & the S60 browser.
Test: You're using an Android device: false
Test: You're using an Android device with a WebKit-based browser: false
// Detects if the current browser is on an Android-powered device. $uagent_obj->DetectAndroid(); // Detects if the current browser is WebKit-based on // an Android-powered device. $uagent_obj->DetectAndroidWebKit();
Detect Windows Mobile Devices
Devices running Windows Mobile are fairly popular in the U.S., especially among corporate IT departments. This code detects both the non-touch screen (Standard/Smartphone) and touch screen (Professional/PocketPC) types of devices.
Why detect this browser? Pocket Internet Explorer and Opera for Windows Mobile are moderately capable mobile browsers. Don't send users to barebones WAP/WML pages! Instead, give these users either modest desktop pages (avoid AJAX and complicated CSS) or nicely formatted mobile-optimized content. (The latter is probably the better choice.)
Test: You're using a Windows Mobile device: false
// Detects if the current browser is a Windows Mobile device. $uagent_obj->DetectWindowsMobile();
Detect BlackBerry Devices
The most popular smartphone platform in the United States. (Still beats the iPhone in sales!) Unfortunately, the BlackBerry browser isn't great.
Why detect this browser? Although the browser isn't as capable as the WebKit ones noted above, it can display nicely (but minimally!)-formatted mobile-optimized content. At least when the browser is set to HTML mode! Otherwise, in WML-only mode, it should be sent the barebones WAP/WML pages.
Test: You're using a BlackBerry: false
// Detects if the current browser is a BlackBerry of some sort. $uagent_obj->DetectBlackBerry();
Detect PalmOS Devices
Last, but not least, in the smartphone category are PalmOS devices. These devices are still fairly popular in the U.S., if less so abroad, and there is a large installed base of PalmOS devices.
Why detect this browser? As the device which practically invented the smartphone category, PalmOS devices ship with a browser and a good number of users have data plans. Unfortunately, I don' t have a PalmOS device in my device library yet, so I can't make any content format recommendations. (Anyone want to give me a U.S. market unlocked GSM Centro?)
Test: You're using a PalmOS device: false
// Detects if the current browser is on a PalmOS device. $uagent_obj->DetectPalmOS();
Additional API Testing
Now that we've seen the general pattern for how to use our PHP uagent_info object, let's see the full list of what it can detect. In the interest of space, we won't show the code for each. (But you can download it above!)
- This is any smartphone-class device, DetectSmartphone(): false
- This device's browser is based on WebKit, DetectWebkit(): false
- Quick check to see if this is a mobile device. Ought to detect most modern mass market phones and smartphones, DetectMobileQuick(): false
- Longer, more thorough check to see if this is a mobile device. Ought to include the Nokia Internet Tablet and game consoles, DetectMobileLong(): false
- This device's browser supports WAP/WML content, DetectWapWml(): false
- This device supports Java MIDP, DetectMidpCapable(): false
- This device is BREW-powered, DetectBrewDevice(): false
- This is a Danger Hiptop, DetectDangerHiptop(): false
- This is a Nokia Internet Tablet (770, N800, or N810), DetectMaemoTablet(): false
- This is a Sony Mylo, DetectSonyMylo(): false
- This is an Archos media player/tablet, DetectArchos(): false
- This is a game console (e.g., Xbox, Wii, Nintendo DS, PSP), DetectGameConsole(): false
Your UserAgent String
It would probably help to know what your browser is reporting in it's UserAgent string...
"ccbot/1.0 (+http://www.commoncrawl.org/bot.html)"
HandsetDetection.com
If you have the technical chops, you might consider registering with a very good (and free!) service called HandsetDetection.com and integrating their service into your site. The service can tell you not only what class of device is visiting your site, but also what the manufacturer and model number are, tons of additional details (e.g., screen size), and even the geolocation of the device. Plus, the site offers lots of reporting metrics about visitor devices. Hand Interactive doesn't currently have any affiliation with them, but we thought you should know about this cool service anyway!
WURFL
The most comprehensive source for mobile device (browser and otherwise) is probably WURFL. It's an excellent free & open source project with an active user community that is constantly updating its device database. WURFL is also a more heavy weight implementation than our PHP code, but can provide detailed handset statistics. (HandsetDetection.com also uses WURFL!)
UserAgent String Resource
Zytrax has a fairly comprehensive list of UserAgent values for mobile devices: www.zytrax.com/tech/web/mobile_ids.html
Enjoy the fun at home!
Download the PHP code described here: mdetect_php.txt.
Note: We've casually tested this code on all of the major smartphone platforms and a handful of mass market phones, plus the Nokia Internet Tablets. So far so good!
That being said, the most important caveat is that you should thoroughly test the code for yourself based on your own needs and expectations -- and always using your high priority target devices!
And if you find this code useful, please consider donating so we can purchase additional devices on our testing wishlist!
Code License Information
The code, "Detecting Mobile Devices Using PHP" by Anthony Hand is licensed under a Creative Commons Attribution 3.0 United States License.
Market Share Statistics
- U.S. Market Share, Q1 2008: Read this article at InformationWeek, May 30, 2008.
- World Market Share, Q4 2007: See this press release from Canalys, February 5, 2008.