Mobile Browser Detection

Mobile Browser Detection

Tutorial Details
  • Technology: HTML5 Apps
  • Difficulty: Beginner
  • Completion Time: 20 - 45 Minutes

When creating mobile web apps like our wordpress theme series, it is important to be able to detect a mobile browser and serve the appropriate mobile version. Many readers requested information on how to do this in the comments, so here it is! First, we will cover a wordpress solution, then a PHP solution, and then a popular existing solution. By the end of this tutorial, you will be exposed to the whole spectrum of options and well equipped to handle this scenario!

In MyTouch

With wordpress, we have a lot of tools out there already to help us, including plugins. One terrific plugin out there is MobilePress. MobilePress allows wordpress users to automatically use a mobile theme for mobile users, but more importantly, the plugin allows custom mobile themes to be uploaded and utilized. This will allow us to upload the theme we created and serve it to only the mobile browsers that visit the site.

MobilePress

Upload MyTouch

In order to use a second mobile theme for a site, you first need to define the directory where you will put your mobile themes in MobilePress. If you click on MobilePress on the wordpress admin side panel, you will see an input field for this directory. By default, the directory is wp-content/mobile-themes. We will stick with that.

Options

Upload your theme to this directory, and then click on MobilePress > Themes and select our theme.

MyTouch

Click on the theme to enable it for the default mobile browser. Then click the Default Browser dropdown. Select iPhone browser and click change. Then click on the myTouch theme again to select it for the iOS Safari browser. The Default Browser is for all mobile devices besides the iPhone.

iPhone Testing

iTouch

Android Testing

Android

Now we can serve the appropriate theme to all users! But what if you’re not running WordPress?

Detecting Mobile Browsers Using PHP

There is no PHP function like is_mobile() or anything (although there is a get_browser() function, but that’s a different article!). What we need to do is detect the browser type. Then, based on that information, we will redirect the user to a specific URL. Every browser has a little information attached to it that the server detects. This is called the user agent. The user agent is basically the name of each browser. No, not just the first name, like Internet Explorer or Safari, but the entire name that tells the browser’s story. This includes OS version, platform, etc. As you’d probably guess, we can do a lot with a user agent. We could direct a user based on his or her operating system or even just their version of operating system. This is how some websites, for example a software download page, will automatically give you the correct version of their software.

How to Get Browser Type

It turns out that we can access the browser’s user agent through a super global variable array called $_SERVER[]. The server array allows us to gain a lot of information, but what we want is the browser agent:

$_SERVER['HTTP_USER_AGENT']

This variable will give us a lot of information, but will vary from browser to browser. Here is mine:

Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.125 Safari/533.4>

Can you tell what browser I’m using? Safari? Nope, Chrome. Sorry, I gave you a tricky one! Chrome’s user agent is a bit tricky as it is based on Apple’s WebKit. Now that we have this variable, what are we going to do with it?

The Procedure

Before we go any further, we need to think about what exactly we want to do. We want to detect the user agent using the global variable above, but then what? A simple IF statement to check if the user agent above matches a list of user agents would work. If it does, we can simply redirect the user to the mobile version.

Regular Expressions:

The problem with the user agent is it’s so unique to each person’s setup. There are many hundreds of different versions of browsers, many different operating systems, and multiple versions of every one of those systems and platforms. There are literally thousands of possible combinations that a user agent could be. It would simply be inefficient, non-inclusive, and inflexible if we tried to exactly match strings the old fashion way. Instead, we will use the smart and agile way. We will use regular expressions. Now, if you cringed at the mention of the phrase “regular expression,” that is okay. You understand the ninja-like power that regular expressions give us. This is not a tutorial about regular expressions. You need a whole series for that. Like this one by the great Jeffrey Way. Luckily, we don’t need anything complicated for this situation, so it won’t be too difficult.

preg_match()

Preg_match() is a PHP regular expression function that searches for a certain pattern like a string in a larger string. Preg_match is very capable, but we will only focus on the basics. This is all you need to worry about:

$pattern = "The pattern of smaller string we are searching for"
$subject = "The larger body of text of data that we are searching. This doesn't have to be a string, but in this case it will be. It will be the user agent. In this case the the pattern string is not here so no results will be found"
preg_match ( string $pattern , string $subject )

The nice thing about this is it uses regular expressions so we have a ton of flexibility. If we want to search case insensitive we can:

//The i after the delimiter creates a case insensitive search
preg_match("/iPhone/i", "iphone is a great phone.")

If we want to search for whole word matches, we can do that too:

//The b in the pattern delimiter indicates a word boundary. This will prevent any partial matches like "iPhoney"
preg_match("/\biPhone\b/i", "iphone is a great device..")

Putting this together with an IF statement

We now need to put this together with an IF statement to check for results. This is pretty simple:

$agent = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/iPhone/i', $agent)){
    echo "You're using an iPhone.";
}

As you can see, the above only searches for iPhones. When an iPhone is detected, the script will execute the echo statement.

Extending the Search

The more comprehensive we get, the more phone devices we will cover, but we really are just creating a giant laundry list of mobile devices here. Luckily, we don’t need to repeat the function. That’s what I’ll show you next. By simply adding a pipe character (i.e. | ), we can create essentially an OR statement:

$agent = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/iPhone|Android|Blackberry/i', $agent)){
    echo "You're using a mobile device.";
}

Although we account for a huge majority of mobile browsers by just listing those three devices, the rest of the small remaing percentage of mobile usage is spread out among many other phones. For now, instead of listing out hundreds of phones, we will leave it at that. You will see later in this tutorial how we will address this problem.

Redirect

Once the browser is detected as mobile, we need to redirect to a mobile page. We can simply use the PHP header function for this. All you have to do is specify a location. Here is the complete script:

<?php
$agent = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/iPhone|Android|Blackberry/i', $agent)){
    header("Location: mobile.html");
    exit;
}
?>

The exit just makes sure we don’t execute anything else before the redirect.

Integrating DetectMobileBrowser.com

Now that you know the theory behind browser detection and redirection, we can talk about other options. DetectMobileBrowser.com is a great resource. Not only do they provide a web service, but they also provide an open source solution for almost any language you’d need it in. The best part though is they took the time to create a much larger pattern of mobile browser potential strings to search through. This makes the list much more thorough.

Web Service

If you don’t mind having a 3rd party link, using the simple web service is a great solution. You can direct users to the easy to generate link, and the site will send them to a different URL depending on if it is a mobile browser or not. It’s very simple in structure. http://detectmobilebrowser.com/desktopulr|mobileurl

Mobile Browser

Download in your language

If you don’t want to use a 3rd party link, you can download a script in your language of choice by clicking on Download Scripts. This will reveal 10 different options. If you look at the source, you will see that this list is definitely as comprehensive as it gets, and is a very similar method to ours. From there, you can implement it on your own server or site.

Mobile Browser

After you download, implement it on your server like you would the one we created. The only thing you need to change is the redirect URL:

<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))
//Redirect URL
header('Location: mobile.html');
?>

Wrap Up

Now that we covered mobile browser detection, the theory behind it, and some popular solutions, you should be well equipped to implement a similar system in your own projects! I hope you found this tutorial informative and useful, and let me know if you have any questions or remarks in the comments section!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.alex-grover.com Alex

    Thank you so much for writing this article! I have been searching for a decent non-javascript method to detect mobile browsers.

  • http://mobilizeme.com Marc Guay

    No mention of fore-runner WURFL = lame.

    http://wurfl.sourceforge.net/
    http://www.tera-wurfl.com/

  • http://www.thedevelopertuts.com thedevelopertuts

    Wow, that’s a huge regexp, it will take me a whole night to understand it, and probably a few seconds for the server to understand it either :)

  • John

    How can one distinguish between “iPhone 4″ and the other iPhone’s?

    • http://www.connorzwick.com Connor Zwick
      Author

      Unfortunately, the user agent of an iphone 4 is this:

      Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7

      It does not specify a device model only a firmware version. Therefore, 3gs models that have upgraded firmware to 4.0 will have the same user agent.

  • Dru Martin

    Thanks for this. It’s just what I was researching how to do!

    One question, is it typical to format a webpage for each platform like: redirect iPhone to (this URL), redirect android to (this URL), redirect general mobile user to (this URL). And if so, how can we differentiate between user agents and which URL they get sent to?

    @Marc Guay: I’ve read a bit about WURFL but haven’t the slightest clue how to implement it. Any advice would be lovely!

  • http://twitter.com/chadsmith Chad Smith

    You mentioned detectmobilebrowsers.mobi as having the web service and all the languages. The correct site is http://detectmobilebrowser.com/

    • http://mobile.tutsplus.com Mark Hammonds

      Thanks for this. The link has been updated!

    • http://connorzwick.com Connor Zwick
      Author

      Thanks Chad! My bad.

  • http://www.connorzwick.com Connor Zwick
    Author

    For anyone that did not see it, the mobile browser detection article is now online:

    http://mobile.tutsplus.com/tutorials/html5/mobile-browser-detection/

  • http://christophkock.com chris

    thank you for this nice article

    best regards

  • http://rightmindcreative.com Ryan Stang

    Ok, so we can easily redirect to a mobile specific theme/file/directory. But what happens if the user decides they would rather use the full version of a site. What kind of code is behind a link on the mobile version of a site that will override the auto redirect and allow users to the full version of the site.

    Doesn’t forcing mobile users to use only the mobile site infringe on a sites usability?

  • http://egamifxstudio.com Dethel J. Mateo

    Hello,

    where do you put this code in the html file?

    –Thanks

  • http://www.handsetdetection.com Richard

    You could also try Handset Detection for mobile browser detection & redirection. Its got a wizard that lets you create javascript snippet you can paste into your std site.

    @Ryan : The trick is to check the http referrer. If the referrer is local (ie from your mobile site) then dont redirect back to the mobile site. Its built into our wizard, of course. :-)

  • http://wedesignapps.com Christopher Chance

    Excellent article. I tried both the wordpress plugin and the mytouch theme created by this tut. It was very slow on Android and the text is totally weird. Content gets cutoff and images get squashed. There are lots of issues with this theme although it is a good start for a basic tutorial.

  • Amit

    Use http://51degrees.codeplex.com/. It is an ASP.NET open source module which detects mobile devices and provides auto redirection to mobile optimized pages when request is coming from mobile device. It makes use of WURFL mobile device database. For redirection there is no need to modify existing ASP.NET web application pages.

  • awojo

    Does anyone know how to have the auto redirect in place but then have a link on the mobile website to allow them to go to the full site without getting caught in the never ending cycle of being auto redirected back to the mobile site?

    Facebook, Google and Walmart all have the option to view the full site from their mobile sites.

    Any help would be greatly appreciated!

  • http://radongas.blogspot.com Micah Burke

    Here is how to provide access to the non-mobile site for folks who want to view it:

    <? php

    if (empty($_GET['mobile'])) {

    $useragent=$_SERVER…

    }

    In other words, look for a $_GET variable and place the useragent checking code inside curly brackets { }…

    In your link to the non-mobile site ie: "Click here to go to full site." Place anything in the variable for mobile.

    Click here to go to full site.

    That will tell the php code to skip browser detection.

    • http://www.edwinraja.com Mobil

      Thank you Micah Burke!

  • M Burke

    Sorry, that last part should read:

    Click here for full site.

  • M Burke

    Ok, for some reason everything got messed up.

    <?php if (empty($_GET['mobile'])) {

    $useragent=$_SERVER['HTTP_USER_AGENT'];
    if(preg_match(‘/android|avantgo…

    header(‘Location: http://www.yoursite.com/mobile.html‘); }
    } ?>

    Then, on your mobile page, put a link back to the main page but send a variable to ‘mobile’:

    <a href=”http://www.yoursite.com/index.php?mobile=no” > Press here to view full site </a>

    • vincenzo

      Hi M Burke my website is powered by wordpress, I used the code php of the page:

      http://detectmobilebrowser.com/

      with your modification. I included the code in the page header.php:

      in the mobile version of the website I put the code:

      Full version

      When I click on the link “full version” of the website mobile every think works perfectly. But when I am in full version and I click on the navigation bar to change the page sends me back into the mobile website

      Can you help me tks lot
      Vincenzo

  • Kim

    Is there a way to detect for just Iphone users and not Ipad users?

    • http://rufer-design.com/ Steffen Ruefer

      You could use media queries based on screen resolution detection. A good example for that is implemented by the Less Framework: http://lessframework.com/. The main issue is that it does only use screen detection and not browser specifics, i.e. any device with the same screen resolution as the iPhone would be using the same CSS.

  • Matt

    Quick question.

    I would like to implment this but I am a little confused on what I need to do here. I would like to use the jquery downloaded file but don’t know what I need to change in order for this to function properly.

  • korman2

    Excellent post, but I have one question, what if i have a link from my mobile site to my full site? How redirecting to it without looping back to movile version?
    Thanks for your knowledge.

  • kwitelle

    Hi,

    I would like to install a Mobile browser detection on my site. So I studied your article, and I can follow quit good but when you talk about :

    “After you download, implement it on your server like you would the one we created.”

    Where exactly in my website do I need to put this PHP script that I downloaded?

    Thanks for you reply

    Regards
    Kwitelle

  • paso

    MobilePress. no longer exists?!
    We couldn’t find that plugin.

  • BSPR

    Hey Micah where would you put the code you suggested in order to make the view full website work, rather than work only if you click it each time. So you know I found this code in the check.php file in mobilepress plugin.

    <?php
    if ( ! class_exists(‘MobilePress_check’))
    {
    /**
    * Class that does all the checks to determine if we are dealing with a Mobile browser
    *
    * @package MobilePress
    * @since 1.0
    */
    class MobilePress_check {

    /**
    * Initialize the checking of the mobile browse
    *
    * @package MobilePress
    * @since 1.0
    */
    function init()
    {
    // Get the theme we need to render
    $this->theme = mopr_get_option(‘default_theme’, 1);

    // If viewing the mobile website
    switch(TRUE)
    {
    // ?mobile accesses the mobile version of the website
    case (isset($_GET['mobile'])):
    $browser = “mobile”;
    $activated = TRUE;
    break;

    // If forcing iphone theme
    case (isset($_GET['iphone'])):
    $browser = “iphone”;
    $activated = TRUE;
    $theme = mopr_get_option(‘iphone_theme’,1);
    break;

    // ?nomobile renders the orignial website
    case (isset($_GET['nomobile'])):
    $activated = FALSE;
    $theme = ”;
    break;

    // Apple/iPhone browser renders as mobile
    case (preg_match(‘/(apple|iphone|ipod)/i’, $_SERVER['HTTP_USER_AGENT']) && preg_match(‘/mobile/i’, $_SERVER['HTTP_USER_AGENT'])):
    $browser = “iphone”;
    $activated = TRUE;
    $theme = mopr_get_option(‘iphone_theme’,1);
    break;

    // Other mobile browsers render as mobile
    case (preg_match(‘/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i’, $_SERVER['HTTP_USER_AGENT'])):
    $browser = “mobile”;
    $activated = TRUE;
    break;

    // Wap browser
    case (((strpos(strtolower($_SERVER['HTTP_ACCEPT']),’text/vnd.wap.wml’) > 0) || (strpos(strtolower($_SERVER['HTTP_ACCEPT']),’application/vnd.wap.xhtml+xml’)>0)) || ((isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])))):
    $activated = TRUE;
    break;

    // Shortend user agents
    case (in_array(strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,3)),array(‘lg ‘=>’lg ‘,’lg-’=>’lg-’,'lg_’=>’lg_’,'lge’=>’lge’)));
    $browser = “mobile”;
    $activated = TRUE;
    break;

    // More shortend user agents
    case (in_array(strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4)),array(‘acs-’=>’acs-’,'amoi’=>’amoi’,'doco’=>’doco’,'eric’=>’eric’,'huaw’=>’huaw’,'lct_’=>’lct_’,'leno’=>’leno’,'mobi’=>’mobi’,'mot-’=>’mot-’,'moto’=>’moto’,'nec-’=>’nec-’,'phil’=>’phil’,'sams’=>’sams’,'sch-’=>’sch-’,'shar’=>’shar’,'sie-’=>’sie-’,'wap_’=>’wap_’,'zte-’=>’zte-’)));
    $browser = “mobile”;
    $activated = TRUE;
    break;

    // Render mobile site for mobile search engines
    case (preg_match(‘/Googlebot-Mobile/i’, $_SERVER['HTTP_USER_AGENT']) || preg_match(‘/YahooSeeker\/M1A1-R2D2/i’, $_SERVER['HTTP_USER_AGENT'])):
    $browser = “mobile”;
    $activated = TRUE;
    break;
    }

    $_SESSION['MOPR_MOBILE_BROWSER'] = $browser;
    $_SESSION['MOPR_MOBILE_ACTIVE'] = $activated;
    $_SESSION['MOPR_MOBILE_THEME'] = $theme;
    }

    }
    }
    ?>

  • BSPR
  • Andy

    I used this code from M Burke to offer a way back to the full website from the mobile version:

    And the link on the mobile site:

    Go to full site.

    It works as it should but when I’m back on the full site, navigating away from the home page will cause header errors (since I’m using wordpress, each page shares the same header.php file) as well as when clicking on the home page link it will redirect back to the mobile site since the GET variable is no longer set.

    Anyone have any ideas on a workaround for this?

  • http://www.apachemobilefilter.org Idel

    Ty to see also Apache Mobile Filter (http://www.apachemobilefilter.org) is free and is easy to install.

  • http://www.theitechblog.com/ Namit Gupta

    How can I make WordPress not to redirect on mobile theme (mobilepress) on iPad? any solution? I want the normal desktop theme of my site to show up when anyone opens my site on iPad.

  • http://www.browserleaks.com DNT

    This is wrong approach! You need to detect features, not id strings
    https://developer.mozilla.org/en/Mobile/Viewport_meta_tag

  • Rohan

    Nyc tutorial!

  • Serban

    @DNT you can detect features only client-side, which means an extra HTTP request.
    It’s okay to try to detect the mobile device server-side.
    I suggest you also use Mobile_Detect class from http://code.google.com/p/php-mobile-detect/

  • http://toms2012.webeden.co.uk TOMS sale

    “suspended”

  • http://technoleash.com Nehal Kabra

    Was looking one for my blog as well. Thanks for the help, let me try !

  • http://www.facebook.com/ty.buchanan.75 Ty Buchanan

    Just give us the damn code to put in the webpage and script for the PHP file on the server.
    The rest is absolute crap!. We know how to write an html page in a “mobile” subdirectory.

  • http://www.gadgetsviews.com/ Waheed Mahmood

    thank you for this nice article