Detecting Browsers of iPhone, iPod, iPad, Android and BlackBerry with JavaScript and PHP

Detecting Browsers of iPhone, iPod, iPad, Android and BlackBerry with JavaScript and PHP

To begin with, we need to understand that in the HTTP protocol, browser send its identity called user agent to the server to request the wanted webpage. Every browser has its only unique user agent value, and therefore we can check that value to identify the user browser. So, first we have to take a look at some examples of user agents of mobile devices.

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   

Android user agent (another one)

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  

After all, in programming, we gather these data to do the checking. First in JavaScript:

if (/(iPhone|iPod|iPad)/.test(navigator.userAgent)) {  
  /* This is iOS */  
}  
if (/Android/.test(navigator.userAgent)) {  
  /* This is Android */  
}  
if (/BlackBerry)/.test(navigator.userAgent)) {  
  /* This is BlackBerry */  
}  
if (/(iPhone|iPod|iPad|BlackBerry|Android)/.test(navigator.userAgent)) {  
  /* This is one of the mentioned mobile device browsers */  
}  

And this is how it works in PHP:

if (preg_match('/iPhone|iPod|iPad/', $_SERVER['HTTP_USER_AGENT'])) {  
  /* This is iOS */  
}  
if (preg_match('/Android/', $_SERVER['HTTP_USER_AGENT'])) {  
  /* This is Android */  
}  
if (preg_match('/BlackBerry/', $_SERVER['HTTP_USER_AGENT'])) {  
  /* This is BlackBerry */  
}  
if (preg_match('/iPhone|iPod|iPad|BlackBerry|Android/', $_SERVER['HTTP_USER_AGENT'])) {  
  /* This is one of the mentioned mobile device browsers */  
}