Video icon 64
Learning to code? Skill up faster with our practical video courses. Start your free trial today.
Advertisement

Mobile Browser Detection

by

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!

Advertisement