Thursday 25 Nov 2010

Better PHP mobile phone detection

PHPWhen I was searching how to detect the portable phone and other small mobile devices to create mobile versions of my web sites, I see several times a really bad PHP code! :-o

There's even a company specialized in mobile sites creation who send me this code to use it on a client's site. So I use this base to rewrite a faster and better code!


The "accused" code is visible on Mobiforge.

Why is it bad? Because it's composed of 5 tests to detect if the user agent ($_SERVER['HTTP_USER_AGENT'] in PHP) is the one from a browser for mobile or a standard navigator. But these 5 tests are systematically done.

Even if PHP has already discover it deals with a mobile, it continues to execute the other tests! Especially that the 1st test uses preg_match, it is very powerful and detects 99% of the mobiles. It would be thus useless to continue!

In the same style DetectMobileBrowsers propose a very complete code. This time, it stops as soon as we're sure to have a mobile, but the tests are heavy (using preg_match!) and in the worst case (desktop computer), it runs 11 tests to complete! If you don't need all the precision it brings, you'd better to look mine. ;-)


Here's my code:

function mobile_detection ()
	if (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE']))
		return true;

	if (isset ($_SERVER['HTTP_ACCEPT']))
		$accept = strtolower($_SERVER['HTTP_ACCEPT']);
		if (strpos($accept, 'wap') !== false)
			return true;

	if (isset ($_SERVER['HTTP_USER_AGENT']))
		if (strpos ($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false)
			return true;

		if (strpos ($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false)
			return true;

	return false;

I write first the most simple test, to exit the function with the less possible operations. In the worst case, we only do 3 tests, really a lot faster than those based on preg_match!

This small test works with the default Android browser, Safari for iPhone, Opera Mini and Mobile, the Wap navigators, the mobile version of Google bots (I don't know how to test other search engines). If you have a mobile browser that is not detected, I would be pleased to learn it. ;-)


If you really want to be certain, you can add a final test in the if (isset ($_SERVER['HTTP_USER_AGENT'])) loop:

if (preg_match('#Android|BlackBerry|Cellphone|iPhone|iPod|hiptop|HTC|MIDP-2\.|MMEF20|MOT-V|NetFront|Newt|Nintendo Wii|Nintendo DS|Nitro|Nokia|Opera Mobi|Palm|PlayStation Portable|PSP|portalmmm|SonyEricsson|Symbian|UP.Browser|UP.Link|webOS|Windows CE|WinWAP|YahooSeeker/M1A1-R2D2|LGE VX|Maemo|phone)#', $_SERVER['HTTP_USER_AGENT']))
  return true;


Then to use this code, we can simply send a modified CSS style adapted to the mobiles. This seems a better solution than having two sites with two different URL, but the same content!

if (!isset ($_SESSION['mobile']))
  $_SESSION['mobile'] = mobile_detection();
if ($_SESSION['mobile'] == true)
  echo '<link rel="stylesheet" type="text/css" href="style/version-mobile.css" />
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=0.25" />';

With that, you can also see the meta I use on the mobile phones versions (that don't block the zoom like some websites do, even big ones!). More information on the meta for mobiles on Learn the Mobile Web.


Ideally add a link/form to switch from desktop version to mobile version, in case of error or simply for a user who prefer the other version. That's the reason why I use a session to keep the user preferences.

We can also instantly switch from a version to the other, even in keeping the preference with a cookie, by using Javascript. See an example on this site or Movies.Kiao, the "Mobile version" text changes the CSS immediately and keeps the choice in a cookie created by Javascript. Read the next article switch CSS with Javascript to learn this method. The good reasoning is to suggest the mobile CSS style, without impose it. :-)

café Did this article help you? 
Buy me a coffee!

6 answers at “Better PHP mobile phone detection”

  1. Backlink from Tweets that mention Better PHP mobile phone detection - HTML & CSS - Azure Dev --
  2. Backlink from Activate mobile style in Javascript - HTML & CSS - Azure Dev
  3. 1
    Richard ( said:

    The difficulty with hard coding regular expression matches is that new browsers arrive and things stop working or worse, all your android tablets get sent to your mobile site. We made to get around these problems. Its a real tim database of mobile devices and all their capabilities.

  4. 2
    augment said:

    What a great job you've done of simplifying something that’s been so hard to find a straight answer for while searching online.

  5. 3
    budflick ( said:

    this is useful. im testing the code. btw will it detect "mozilla" phones correctly? i had problems in the past, some nokia/symbian carry a useragent "Mozilla 5.0" eventhough the native browser is being used, therefore leading them into the desktop site.

  6. 4
    David ( said:

    I can't say. Maybe they will be detected with the 2 first conditions. :-|

Leave a comment (all comments are moderated, don't waste time with spam)

Azure Dev