Detecting iPhone, iPod, iPad, Android and BlackBerry browser with JavaScript and PHP

April 20th, 2011 by Alex Leave a reply »

Detecting mobile browsers may be useful in case you want to show a special download link or a promotion for someone going mobile. In pure javascript, the implementation is dead simple. Here we have example user agents of mobile browsers:

iPhone user agent

Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3

iPod Touch user agent

Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3

iPad user agent

Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10

Android user agent

Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2
Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17

BlackBerry user agent

BlackBerry9000/4.6.0.266 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/120

So, as we see, all we need is find those special iPod or Android strings in user agent, something like this:

var ua = navigator.userAgent;
var checker = {
  iphone: ua.match(/(iPhone|iPod|iPad)/),
  blackberry: ua.match(/BlackBerry/),
  android: ua.match(/Android/)
};

And then we can do like this:

if (checker.android)
  // show something special for Android

For PHP we can use same technique, except that user agent will be retrieved like this:

$ua = $_SERVER['HTTP_USER_AGENT'];
$checker = array(
  'iphone'=>preg_match('/iPhone|iPod|iPad/', $ua),
  'blackberry'=>preg_match('/BlackBerry/', $ua),
  'android'=>preg_match('/Android/', $ua),
)

And then using it like this

if ($checker['iphone'])
  // do something for iPhone

This page can be found by searching for:

jquery detect blackberryhow to detect iphone androidjavascript detect iphone androidjquery detec android iphone ipadipod agent androidjavascript detect iphone or androidjavascript detect androiddetect iphone android javascriptjquery detect iphone ipad androidjavascript detect android version