iPad Detection Using JavaScript or PHP

iPad

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

// For use within normal web clients 
var isiPad = navigator.userAgent.match(/iPad/i) != null;

// For use within iPad developer UIWebView
// Thanks to Andrew Hedges!
var ua = navigator.userAgent;
var isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua);

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.


Comments

  1. Carlos cardona

    Nice tutorial. Did you get an iPad? I also created a similar tutorial
    http://cardonadesigns.com/wordpress/2010/04/04/using-php-to-detect-the-ipad-user-agent/

    • jQuery Howto

      I just wrote a similar post, and referred your post.

      As I described the technique in the post, it’s better to apply different CSS to iPad visitors rather than redirecting them to a special version of your website (when it meets your requirements). This way all you need to do is manage different CSS files.

      http://jquery-howto.blogspot.com/2010/10/javascript-to-detect-ipad-visitors.html

    • Dave

      I respectfully disagree. Especially if your site has flash, more than a one column layout, or really bandwidth intensive content.

      Standard web and mobile web are completely different beasts. Simple css tweaks may not be enough.

      I applaud the idea of keeping maintenance easy but I think anyone who is even thinking of doing a mobile site, will have to prioritize which content to show.

  2. Tim Wright

    The cruddy thing about the iPad user agent string is that it has the word “mobile” in it. So if your detection script is looking for “mobile” already, it may also be sending iPad users to your iphone/mobile optimized site. Apple offered up a way to test though -> http://developer.apple.com/safari/library/technotes/tn2010/tn2262.html

  3. Rob

    Great! Now I can redirect/block iPad users!

  4. Andrew Champ

    @Rob: That’s what I was thinking! Thanks David.

  5. Andrew Champ

    @Rob: That’s what I was thinking! Thanks David.

  6. Connor Crosby

    I just use this code:

    // <![CDATA[
    if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
    document.location = "WEBSITE GOES HERE";
    }

    • Francisco Escareño

      What if I need a different landing site for the ipad, I try this and it doesn´t work

      if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
      {
      location.replace(“iphone/index.html”);
      }
      if((navigator.userAgent.match(/iPad/i)))
      {
      location.replace(“ipad/index.html”);
      }
      else
      {
      location.replace(“index_frames.html”);
      }

      Thanks

    • Justin

      Maybe try location.href I’ve never used location.replace.

  7. Connor Crosby

    @Connor Crosby: that is in a javascript

  8. John Allsopp

    Another, and often better option is media queries in CSS3

    http://www.w3.org/TR/css3-mediaqueries/

    You can deliver CSS based on device characteristics, such as viewport width, and orientation (so you can have different CSS for portrait and landscape)

    http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/OptimizingforSafarioniPhone.html

  9. Seb

    Let them eat Flash

  10. Exotux

    Welcome to the old web !

    “Site optimised for IE 5.5″

  11. Noetic

    But where is the code to make the iPad melt once detected? :p

    • Windows User

      if (navigator.userAgent.indexOf(‘iPad’) != -1)) {
      document.task = “selfdestruct.html”;
      }

    • Windows User

      if (navigator.userAgent.indexOf('iPad') != -1)) {
      document.location = "automelt.html";

  12. maybe

    @Noetic: you could start with js “while……..” =x

  13. Vincent van Dijk

    Very nice tutorial, tnx man!

    V.

  14. Matt

    I was a little stuck. I’m looking to do something similar, but really just target the viewport for the iPhone/iPod Touch and iPad. Here’s what I came up with so far but doesn’t seem to work. Any suggestions?

    <?
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    if(preg_match("/ipad/", $useragent)) {
    echo '’;
    }
    else if(preg_match(“/iphone/”, $useragent) || preg_match(“/ipod/”, $useragent)){
    echo ”; }
    ?>

  15. Charles

    Hey ! Thanks for the turorial !
    I’m a newbie, and I wanna do something I guess is easy, but can’t find a solution.
    What I wanna do is to display a certain element (a div) if the user is on his computer, but display another one instead if he is on his iPad.

    What should I write, and where ????

    Please help me !

    Charles

  16. jamus

    Perfect! thank you David!

  17. Anthony

    Hi! Thanks for the article.

    I wrote a free open source set of APIs for web designers to detect mobile visitors. The APIs are very light weight, easy to implement, and easily customized. They’re available for JavaScript, PHP, Java, and ASP.NET. Check out http://www.mobileesp.org

  18. jhs

    Nice article, thanks.

    Also nice site and article on iPad site dev Garmahis. Particularly enjoyed the link to page flipping versus scrolling. :)

  19. Luis_green


    $useragent = $_SERVER['HTTP_USER_AGENT'];
    if(preg_match("/ipad/", $useragent)) {
    die("It Sucks....")
    }else
    {
    .
    .
    .
    .
    .
    }
    ?>

  20. Lori Brown

    Thank you very much for this page! I probably owe you a cut of the small fee I earned last night solving someone’s emergency iPod detection crisis. And you’re funny! (lots of people can code. Funny, not so much.)

  21. Morten Skogly

    Did you know that its not possible to copypaste you hillarious quotes when using An ipad to reading you site?

  22. MyShadowSelf

    “determine if the user is being a smug, iPad-using bastard”
    Genius!

    Hate the bastards myself. It’s the iPhone all over again: “You didn’t invent it, you bought it, anyone can buy a bloody iPad”

  23. MyShadowSelf

    Sorry for posting again in such quick succession, but I’ve just found a very natty PHP class that handles all browser user agents, including the iPad. Thought you might be interested:
    http://www.phpclasses.org/package/6369-PHP-Detect-the-type-of-browser-accessing-the-site.html
    Promise I’m not spamming!

  24. Richard

    Nice Article. The regexp works great for single device detections. If you’re after detecting device classes like Tablets or other mobile browsers check out http://www.handsetdetection.com (disclaimer : I work there).

    Cheers
    Richard

  25. Devin Walker

    Awesome tutorial! Saved me for iPad in my use

  26. ipad comparison

    Nice way to check, but I am waiting to buy iPad.

  27. ipad news

    thank you for info

  28. Andrew Hedges

    As of iOS 3.2 (which is iPad-only), the user agent string no longer contains ‘iPad’. Rather, the device identifies itself as ‘iPhone’, so the above solution does not work. The way I’m detecting iPads in JavaScript–at least until I come across a better way–is with the following expression:

    /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua)

    • Andrew Hedges

      Sorry, the ‘ua’ in that line of code should be navigator.userAgent

    • David Walsh

      When is/was iOS 3.2 released? I just tested on my iPad, which has its iOS up to date, and the user agent included “iPad”.

      http://davidwalsh.name/dw-content/detect-ipad-new.php

    • Andrew Hedges

      I’m seeing iPad in the UA for Safari on iPad as well. I think the case I was seeing was an embedded UIWebView inside an iPad app. Most web developers won’t have to worry about that case, I suppose, but it is pretty vital for native app developers using web views.

    • David Walsh

      Awesome, thanks Andrew. I updated my article. Cheers!

  29. Frank

    Laughed my ass off on the ‘iPad this, iPad that, iPad your mom’. hahaha! Made my day!!!

  30. Thumbnail

    Nice article, but the PHP is kinda, wierd?!

    personally I should use this:


    because strpos isn’t ment to do that, it wil work anyway

  31. Thumbnail

    Hopefully the code will work now

  32. Luis Merino

    To those having issues like “too many redirections” there’s a solution, here’s the link of StackOverflow where this guy helped me figure out a easy solution to this!

    http://stackoverflow.com/questions/5131158/ipad-iphone-browser-sniffer-with-mod-rewrite-and-redirection-too-many-redirecti

  33. André Dal Molin

    Hey, becareful with this line:

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

    PHP’s strpos() can return 0, meaning that the $needle is at position 0 (zero) of the string. So if you do like that, $isiPad can return FALSE where the correct value is TRUE.

    To resolve that, do this:

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

    :)

    • Dobes

      That is true in general, but in the case of the user-agent string for iPad it never puts iPad at the start of the string…

  34. Efrenk

    Palomita para tí, awesome tutorial, simply! efficient! Thanks a lot.

  35. Kumanan Lingan

    Thanks for the code snippets David…! Thanks for Andrew too.

  36. Blunt Brother

    Surely there must be a better way than using userAgent…
    At the end of March 2011, there are literally HUNDREDS of possible values for the userAgent, all of which have to be manually mapped as “true” or “false” as to whether they are mobile devices.
    In the coming months and years, that number could easily become THOUSANDS!!!
    This is a regression to web-dev practices of the 1990s.
    As developers, we cannot rely on such tactics…
    Simply including such a file means users have to download SEVERAL THOUSAND ADDITIONAL BYTES just to determine if they are mobile or not.
    Maybe we should be identifying screen resolutions or something “simpler”…

  37. Dave

    @Blunt Brother – someone already commented on this – see CSS3 media queries. I agree with you by the way – user agent sniffing everything is a big regression. We’d just about, almost FINALLY got Microsoft to fix IE and the desktop browser space is better than it’s ever been for web developers, so now everyone wants to bend over for mobile devices? Insane.

  38. Sebastian

    How about for ipad 2?

  39. Sonesh

    Awesome post that I was looking for. Although a suggestion : the code with black background is hard to read i had to copy it and read it .

    Thanks again

  40. Ant

    Anyone here had experience detecting iPad then providing a specific version of a video within the page to only thos ipad users, allowing for stack overflow to take care of other safari, ff, and ie users. The reason i need to do this is to overcome ipad 2′s gamma problem when playing video. I need to provide a gamma adjusted version of the video just to ipad users (preferably just ipad2 but i dont think the user agent string is that specific?,

    Ideally just JS, and Im no JS wizard.

    Any help would be greatly appreciated.

  41. Niche Modern

    Just wanted to share this, since it pertains to the topic.

    Our hero image once clicked opens a pop-up/shadowbox image viewer (imaging provided by Adobe Scene 7) on our company website, but (non-Flash-i)Pads don’t dig it. We use Miva Merchant as a part of our backend. The following code, using Miva Script, allows us to detect iPads and reveal a compatible viewer alternately:

    -------- MOBILE USER AGENT --------

    -------- MOBILE S7 VIEWER --------

    -------- MOBILE ENLARGE VIEWS BUTTON --------

    -------- NORMAL USER AGENT --------

    -------- PRODUCT IMAGE --------

    -------- ENLARGE VIEWS BUTTON --------

    Essentially, if the site detects a mobile device, show the alternative viewer. Else, reveal the normal one.

    Thanks for the insight thus far.

  42. Richie

    A fourth method are ESI tags like:

    http://esi-examples.akamai.com/viewsource/ad.html

    This is required when using a server side templating system that renders first before JavaScript

  43. My Bookmarks « Ruman's Blog

    [...] iPad Detection Using JavaScript or PHP [...]

  44. Genesis

    the php code is not working anymore.. :( help anyone?


Be Heard!

Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!

Name*:
Email*:
Website: