Wednesday, August 31, 2011

Detecting mobile browsers in PHP

I was recently trying to find some code to detect if a visitor to my website was coming from a mobile browser so I could give a mobile friendly stylesheet, and after quite a bit of searching couldn't find anything for PHP.

I was able to find lists of mobile client user agent strings, but there are hundreds, and you don't want to be checking against hundreds of strings for every request, as it is slightly time consuming. After a bit more searching I came across this website, which gives a python algorithm for detecting mobile browsers.

The website gives a much smarter approach than checking every possible user agent. It checks for the most common mobile browsers, and if it doesn't find a match, checks against common desktop operating systems and web crawler user agents. If it still doesn't have a match it just assumes that it's a mobile browser. I used this algorithm and put together the following PHP code:


function is_mobile($user_agent, $default_to_mobile = true) {
   // Common mobile browsers
   $mobile_regex = "/iphone|ipod|blackberry|android|palm|windows ce|fennec/i";
   if (preg_match($mobile_regex, $user_agent) === 1)
      return true;

   // Desktop and bots
   $desktop_regex = "/windows|linux|os x|solaris|bsd|spider|crawl|slurp|bot/i";
   if (preg_match($desktop_regex, $user_agent) === 1)
      return false;
   // Assume it's an uncommon mobile browser
   // unless $default_to_mobile is false
   return $default_to_mobile;

So all that is needed to be done once the above code is included, is the following:

if (is_mobile($_SERVER['HTTP_USER_AGENT'])) {
   // use mobile template and stylesheet
} else {
   // use desktop template and stylesheet

Hopefully this saves you the time to track down an algorithm and write the code for it. Let me know if you find this useful or can suggest any improvements.

Until next time, peace.