Thursday, August 9, 2012

How to detect iPhone and iPad's User Agent using PHP or JavaScript


Whenever a user visit your website or a page via iPhone or iPad Apple provides user agent agent.


iPad's user agent string is:

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

The iPhone's user agent string appears as follows:

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

Provided with this information, it's fairly straight forward to use JavaScript to detect the user agent, and send the user to a specific page:
JavaScript Solution
<script type="text/javascript">

if((navigator.userAgent.match(/iPhone/i)) || 

 (navigator.userAgent.match(/iPod/i))) {

   if (document.cookie.indexOf("iphone_redirect=false") == -1) window.location = "http://iphone.yoursite.com/";

}

</script>

PHP Solution
You can achive the same functionality by using server side scripting via PHP,
if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod'))
 {
  header('Location: http://yoursite.com/iphone');
  exit();
}
?>
.htaccess Solution.
You can also use .htaccess file to do the same thing on the server side of things:
RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
RewriteRule ^(.*)$ http://ipad.yourdomain.com [R=301]