Detect mobile browser/user agent with PHP (iPad, iPhone, Android, BlackBerry, WP7 and others)

Posted by Danny Herran on Feb 2, 2011 in Backend | 80 comments

With all this load of smartphones and tablets, it is mandatory for us as developers to optimize our content as much as possible so everybody can see it, no matter what device they are using. This is why I wrote a small but powerful function to properly detect a wide range of mobile devices and redirect to an special content accordingly.

Lets take a look:

function detect_mobile()
{
	if(preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $_SERVER['HTTP_USER_AGENT']))
		return true;

	else
		return false;
}

This function can detect most (if not all) of all the standard “dumb” phones, smartphones, including the iPhone, iPad, Android and Windows Phone 7. Lets say you want to redirect your users to your blog if they are accessing your home page from a mobile device:

$mobile = detect_mobile();

if($mobile === true)
	header('Location: blog');

Nice and easy!

Changelog:

06/06/2012 – Added PlayBook and Kindle Fire support.
16/01/2012 – Rewritten, shortened. Deleted unnecesary checks. Added Windows CE support.
23/05/2011 – Updated for iPod Touch
25/04/2011 – Updated for Windows Phone 7

24/03/2011 – Updated for Android