Mobile User Agent Detection

Recently I was asked to work on a Drupal site that required detection for three different display; tables, mobile phones, and computer screens.

I found code that will allow a detect to all mobiles devices, meaning it will redirect to mobile phones and tables alike. I recommended to use media queries just like what you see currently in the XparkMedia site, but they wanted to display different content and advertising for the different devices. Detection will also allow them keep track and promote just one domain. (no subdomian redirect ).

I started collecting information and doing some research to find the most popular devices and their user agents. Finding the mobile phones was not a problem, but I spend some time to finding the tablets user agents.

The detection is done with php at the server level but it could well be modify to be use with ASP, JAVA or Javascript.

Most Popular Tablets

$user_agent = empty($_SERVER['HTTP_USER_AGENT']) ? false : $_SERVER['HTTP_USER_AGENT'];

if(preg_match('/(ipad|viewpad|tablet|bolt|xoom|touchpad|playbook|kindle|gt-p|gt-i|sch-i|sch-t|mz609|mz617|mid7015|tf101|g-v|ct1002|transformer|silk| tab)/i', $user_agent )  || ( preg_match('/android/i', $user_agent ) && !preg_match('/mobile/i', $user_agent )) ){
	//do something here for tablets
}

Mobile Phones

Now let’s check if it is a mobile phone. It is logical to check for tables first because all tables are mobile devices but not all mobile devices are tables or phones.

if( preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|webos|galaxy|phone|pocket|psp|treo|android|mobile|240x320|400X240|nitro|nokia|portalmmm|proxinet|blackberry|palm||series40|series60|s60|sonyericsson|e10i|samsung|nexus|htc|desire|ipod|itunes|vodafone|wap-|wapi|wapa|wapp|series40|series60|s60|sonyericsson)/i', $user_agent) ){
	//do something here for all mobile phones
}

The previous code is a is a quick an clean way to detect mobile phones here is accurate way to detect mobile phones but It will not detect all.

if ( isset($_SERVER['HTTP_X_WAP_PROFILE']) ||
			isset($_SERVER['HTTP_X_WAP_CLIENTID']) ||
			isset($_SERVER['HTTP_WAP_CONNECTION']) ||
	isset($_SERVER['HTTP_PROFILE']) ||
	isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA']) ||
			isset($_SERVER['HTTP_X_NOKIA_IPADDRESS']) ||
			isset($_SERVER['HTTP_X_NOKIA_GATEWAY_ID']) ||
			isset($_SERVER['HTTP_X_ORANGE_ID']) ||
			isset($_SERVER['HTTP_X_VODAFONE_3GPDPCONTEXT']) ||
			isset($_SERVER['HTTP_X_HUAWEI_USERID']) ||
			isset($_SERVER['HTTP_UA_OS']) ||
			(isset($_SERVER['HTTP_UA_CPU']) && $_SERVER['HTTP_UA_CPU'] == 'ARM')
) {
	// this is a mobile
} elseif ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
	// this is a mobile
}

Download

You can download the full mobile detect file here.