Detecting Mobile Devices Using PHP

Updated November 2009

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("<p>You're using an iPhone: ".$iPhone."</p>");

//You might also want to print out the user agent string.
$agent = $uagent_obj->Get_Uagent();
print("<p>Your user agent string: <br /> ".$agent."</p>");

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 iPad, DetectIpad(): 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 Android Devices

Besides the iPhone, the only other mobile devices in recent times to receive as much attention, both from geeky fanboys and the general public, have been the new devices running Android. Android is a brand new operating system for mobile phones created by Google. Android is a smartphone-class OS with an advanced browser similar to the iPhone's in capabilities.

Why detect this browser? The native Android browser is extremely capable and also based on WebKit, which underlies the iPhone's Mobile Safari & the S60 browser. Generally, if you have web content optimized for the iPhone, also make this content available for Android devices. Additional manufacturers began releasing loads of new Android devices in mid-2009.

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 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 a very capable browser.

Why detect this browser? 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 Windows Mobile Devices

Devices running Windows Mobile are fairly popular in the U.S., especially among business users. 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

Test: You're using a BlackBerry Touch (Storm 1/2): false


// Detects if the device is a BlackBerry.
$uagent_obj->DetectBlackBerry();

// Detects if the device is specifically a BlackBerry Touch
// device, such as the Storm 1 or 2.
$uagent_obj->DetectBlackBerryTouch();

 

Detect PalmOS and WebOS Devices

Last but not least in the smartphone category are devices from Palm. Palm has a new Linux-based operating system for its touchscreen phones launched in mid-2009 call "WebOS". The Pre and the Pixi are the first two WebOS devices. In addition, there is a large installed base of old PalmOS devices.

Why detect this browser? The new WebOS browser shares the same WebKit core as the iPhone's and Android's browsers, though it appears slightly less capable than they are. Still, if a web site is optimized for the iPhone and Android, it may run well on WebOS devices, too. As for older PalmOS devices, I recommend sending them minimally formatted mobile-optimized content.

Test: You're using a Palm WebOS device: false

Test: You're using a PalmOS device: false


// Detects if the current browser is on a Palm WebOS device.
$uagent_obj->DetectPalmWebOS();

// 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 from our new Google Code page!

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!


License Info & Costs

We have moved this code library to a Google Code hosting project and changed the license to an Apache License 2.0, which better fits a free, open source project like this. We've also rechristened this project "MobileESP." For more info, please visit the new MobileESP site: www.mobileESP.org

 

Market Share Statistics


MobileESP Project

Learn more about the new MobileESP project!

We've spun off our mobile device detection code into a FREE open source project called MobileESP! Learn more about it on the new project web site.

Please Donate

If you like and use this code, please consider donating. Any amount is appreciated!

(Please donate -- help us purchase more devices on our testing wishlist!)

About Us

Hand Interactive offers user experience, usability, and business strategy expertise. We're passionate about crafting engaging experiences for mobile, desktop, and web users.

 
Contact us for more information.