Saturday, June 22, 2024

How Can I Detect the iPhone & iPad’s User Agent?

So you’ve decided to create a mobile website for iPhone and iPad users, rather than creating a web applications. Where do you start? This tutorial will show you how to detect the popular mobile devices using JavaScript, PHP and your site’s .htaccess file!

Detecting the iPhone and iPad

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 = “”;

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

if(strstr($_SERVER[’HTTP_USER_AGENT’],’iPhone’) || strstr($_SERVER[’HTTP_USER_AGENT’],’iPod’))

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 ^(.*)$ [R=301]

Now, assuming you want to purchase a ready-made package that detects all mobile devices, you can visit the Detect Mobile Browsers website for their $50 PHP-based mobile device detection script. It is free for non-profit or personal use, however commercial websites need to purchase it. Not only will it detect iPhones and iPads, it will also detect Android, Opera Mini, Blackberry, Palm and Windows devices. You can even use their function generator to create the specific action you wish to, once the user agent is detected. Actions include treating the user agent as a mobile device, directing the user to a specific page for the device, or displaying the page normally as it would for any other browser.

Next week we’ll get into the creation of iPhone and iPad specific websites, show you how to detect and set the iPhone and iPad’s viewport orientation using JavaScript and more!

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles