From The Blog

Detecting the iPhone and iPad

8 February 2012, in HTMLJavascriptPHP

Obviously, if you've created a page specifically for iPhone and iPad users, the first thing you'll need to do is to find out when a user is visiting your site via an iPhone or iPad. Apple provides the iPad's user agent string, which appears as follows:

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:

<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>

Using the same information, you can do the dirty work on the server side using PHP instead:

<?php
if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod'))
 {
  header('Location: http://yoursite.com/iphone');
  exit();
}
?>

Finally, you could always use your site's .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]


Post a Comment