isMobile

Detect a mobile browser or device using PHP

Introduction

Using PHP's preg_match() function, isMobile() searches the user-agent string provided by $_SERVER['HTTP_USER_AGENT'] for carefully selected fragments that detect if a mobile browser is being used, then returns a boolean value for use in your code.

By using isMobile() you can easily create conditional statements that allow you to do things like redirect mobile users to your mobile site or show mobile-only code on your website (e.g., abbreviated forms, mobile ad-units).

Although the source is tiny, the accuracy of isMobile is what makes it a valuable asset. As new browsers and devices come out, isMobile's source is updated here and on the official Github repo.

Source Version 2.1

function isMobile() {
	return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

Parameters

This function does not accept any parameters.

Returns

(boolean) - True if a mobile device is detected, false if failure.


Examples

I often get asked "How can I use this to achieve X" so here are a few of the most common requests.

Place the isMobile() function, followed by the code below, at the top of the file that your server loads when a user goes to your website (e.g., index.php)

		if(isMobile())
			header("Location: http://m.yoursite.com/");
		

Users will be redirected to http://m.yoursite.com/ and all others will see your regular site. Don't forget to change the URL to the URL of your mobile website.

The first 'Redirect a user to a mobile-friendly URL' example on this page won't work in WordPress if you put it in the wrong theme files (e.g., header.php, index.php) because PHP's header() function cannot work if any headers have already been set, which they are by the time WordPress gets to most of your theme files.

Technically you could edit your WordPress's core index.php file as a ‘hack' but that is not recommended since modifying core WordPress files is never a good idea and there's a much better way to do it.

The best way is to place the function, followed by the code below, in your theme's functions.php file. The following code creates a function that handles the detection & redirection so we can tell WordPress to call that function during WordPress's "init" action, which is called before any headers are sent.

		function isMobileForWordPress() {
			if(isMobile())
				header("Location: http://m.yoursite.com/");
		}
		add_action('init', 'isMobileForWordPress', 1);
		

Detection Results

The following are user-agent strings that have been tested against the isMobile() function in order determine its accuracy.

User-Agent:

Mozilla/5.0 (Linux; U; Android 3.0.1; en-us; A500 Build/HRI66) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13

Results

Matched: Android