iPad Detection Using JavaScript or PHP

The hottest device out there right now seems to be the iPad. iPad this, iPad that, iPod your mom. I’m underwhelmed with the device but that doesn’t mean I shouldn’t try to account for such devices on the websites I create. In Apple’s developer tip sheet they provide the iPad’s user agent string:

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

Given that string we can create a few code snippets to determine if the user is being a smug, iPad-using bastard.

The JavaScript

var isiPad = navigator.userAgent.match(/iPad/i) != null;

A quick String.match regular expression test can check for the presence of “iPad” in the user agent string.

The PHP

$isiPad = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad');

This time we look for the position of “iPad” in the user agent string.

The .htaccess

RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
RewriteRule ^(.*)$ http://ipad.yourdomain.com [R=301]

Using some logic from Drew Douglass’ excellent mobile redirection post, we can redirect users to a mobile version of your website if you so desire.

So what would you the above tests for? You may want to redirect iPad users to a different version of your website. You may want to implement different styles to your standard website if your user is surfing on an iPad.

http://davidwalsh.name/detect-ipad