Sign up below to view device data and get your trial account.

We communicate via email to process your request in line with our privacy policy. Please check the box to give us your permission to do this.

Cancel

Choose a category below to quickly discover all our device intelligence articles.


  • Share
  • DeviceAtlas LinkedIn

You are here

Building your own device detection solution

Creating your own internal device detection solution using PHP and Regex is possible, but is it worth the effort? Here are the pro's and con's.

James Kielty - 18 Jul 2019
7 min read

Device detection is the practice of identifying the device requesting your content, accessing your services or viewing your online ads.

In the early days of the World Wide Web, smartphones didn't exist. This meant website owners could focus solely on the desktop experience. Web page layouts and navigation were designed and optimized for large screens and mouse/keyboard interfaces.

In 2007, Apple ruined it all by releasing the first smartphone - the iPhone. This was the first mobile phone that eliminated physical buttons, instead relying on a touch-based interface. It also delivered the internet into the hands of millions of users, leading to web designers and content providers reinventing their efforts to cater to a new wave of small-screen, mouse-less web users.

As smartphone use exploded, eventually overtaking desktop usage in 2016, so too did the range of smartphones on offer. Each had unique selling points and characteristics, which created another level of optimization requirements. No longer was it enough to simply point all smartphone users to a single mobile-web friendly version of your site.

With User Experience also a burgeoning industry, optimizing to the Nth degree was a worthwhile task, maximising ROI.

Creating your own device detection solution

The primary method of differentiating between visiting devices is the User Agent string, the default way for a browser (and a device) to introduce itself when requesting online content from the web server.

The trouble with User Agents is that they aren’t universally consistent. They contain a lot of keywords, many of which are not related to the browser or the device. Browser makers include them just to make sure that the user is not blocked from accessing certain websites, which was a common practice in the 1990s. For example, most UA strings start with the word “Mozilla” even though they have nothing to do with Mozilla’s browser. For example:

Samsung Galaxy S9
Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36
Apple iPhone XS Max (Firefox)
Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/13.2b11866 Mobile/16A366 Safari/605.1.15

Regex

A popular roll-your-own method is to use an internal PHP regex solution, based on a pattern-matching approach on the User Agent strings.

This solution can be a good solution for certain use cases. For example, for smaller websites with a relatively low volume of traffic, or where the site owner is not too concerned about detecting their mobile traffic with very high accuracy. If you simply need to differentiate between mobile/tablet/desktop, this can be useful.

Here is an example of PHP code that could allow basic device segmentation. This was published in 2013 on mobiForge, and helps to show just how quickly the landscape changes, and how difficult a job it would be to maintain an effective list internally.

$tablet_browser = 0;
$mobile_browser = 0;
 
if (preg_match('/(tablet|ipad)|(android(?!.*(mobi|opera mini)))/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
    $tablet_browser++;
}
 
if (preg_match('/(up.browser|up.link|mmp|smartphone|midp|wap|phone|android|iemobile)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
    $mobile_browser++;
}
 
if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
    $mobile_browser++;
}
 
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
$mobile_agents = array(
    'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
    'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
    'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
    'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
    'newt','noki','palm','pana','pant','phil','play','port','prox',
    'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
    'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
    'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
    'wapr','webc','winw','winw','xda ','xda-');
 
if (in_array($mobile_ua,$mobile_agents)) {
    $mobile_browser++;
}
 
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'opera mini') > 0) {
    $mobile_browser++;
    //Check for tablets on opera mini alternative headers
    $stock_ua = strtolower(isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])?$_SERVER['HTTP_X_OPERAMINI_PHONE_UA']:(isset($_SERVER['HTTP_DEVICE_STOCK_UA'])?$_SERVER['HTTP_DEVICE_STOCK_UA']:''));
    if (preg_match('/(tablet|ipad|playbook)|(android(?!.*mobile))/i', $stock_ua)) {
      $tablet_browser++;
    }
}
 
if ($tablet_browser > 0) {
   // do something for tablet devices
   print 'is tablet';
}
else if ($mobile_browser > 0) {
   // do something for mobile devices
   print 'is mobile';
}
else {
   // do something for everything else
   print 'is desktop';
}   
 

Limitations

While you'll get basic category identification using the above approach, there are some limitations to the solution.

  • Accuracy - Regex User-Agent matching can work well in the general case, but will inevitably fail to recognise some portion of devices correctly, e.g. certain Android tablets will be classified as smartphones. While it's possible to add more specific patterns to the regex to match edge-cases by matching specific model numbers, this has the disadvantage of reducing the performance of the detection, and will have knock-on performance implications for your site.
  • Performance - Regular expressions can be slow to execute, particularly for complicated patterns. If performance is a key factor for you, then this is not the way to go.
  • Maintenance - The regex patterns will need to be updated regularly to keep up to date with new devices that may not be already covered.
  • Device capabilities - If you need anything more than simple traffic routing (mobile/tablet/desktop), you'll need to know device properties such as screen size, memory limit, HTML5 support etc. This solution doesn't offer such insights.

A better solution - DeviceAtlas

Creating an internal device identification solution may seem an attractive proposition, but as detailed in the points above, the limitations are likely to result in problems down the line.

Instead of investing many hours into a solution that simply won't stand the test of time, DeviceAtlas can make things a lot easier and future-proof.

Our database is maintained and updated as each new device hits the market, so there's no need for you to constantly worry you're missing out on devices and their specifications.

The most common uses for device detection are:

Content Optimization

One of the most tangible benefits of DeviceAtlas is the content optimization use case. By identifying the specifications of each device (such as screen resolution, connection type, RAM/GPU etc), you can deliver the correct content to each user.

No longer will images display incorrectly, high-resolution videos get wasted on screens that can't display them fully, nor resource heavy downloads be forced on a relatively under-powered device with a slow 3G connection.

Advertising

DeviceAtlas improves conversions and reduces advertising discrepancies by enabling granular device targeting of campaigns.

As well as improving conversions, it enhances analytics and reporting and enables targeting based on a wide range of device characteristics.

Click here to learn DeviceAtlas is used in the advertising industry.

Analytics

Adding device-level data to existing analytics can supercharge your business insights.

It ensures that all areas of a business - marketing, operations and support - are addressing audiences optimally, maximizing customer engagement and revenues/ROI.

Our device recognition capability is highly accurate and lightning-fast, making it an excellent fit for analytics and business intelligence environments where precision reporting is vital.

You can read more about enhanced analytics here.

Apps

DeviceAtlas provides intelligence and analytics on device usage across multiple environments.

It offers the same deep intelligence for native apps as it does the wider web environment. This empowers publishers, advertising platforms and analytics providers to get a consolidated view of device usage across both their web and app offerings.

 

Today, the average person uses 4 or 5 different devices every day. The wider the variety of devices used, the greater the risk is in terms of providing an inadequate user experience, which can negatively affect your bottom line. This means companies need to be on their A-game when delivering effective ways to handle device fragmentation. By integrating a top class device data source into your technology stack, you can get deep, granular information on what devices are accessing your properties and use this intelligence to support content adaptation decisions in real-time.

 

DeviceAtlas - Free Trial

Click below to get access to a fully-working local version trial of DeviceAtlas. This is our high performance flagship product with the most complete data set.

  • Access to locally deployed trial for 30 days.
  • Choice of extensive range of APIs.
  • Device data file covering thousands of devices.
  • Sample code, documentation, and full technical support.

Get Instant access to a DeviceAtlas Cloud trial

DeviceAtlas Cloud offer a great way to start detecting mobile device traffic to your site:

  • Optimize website content for mobile, tablet, and other devices
  • Boost website loading time and minimize page weight
  • Handle traffic from any device as you want

Get started with a DeviceAtlas Cloud trial today.

Get started