Treehouse

iPad Detection Using JavaScript or PHP

By on  
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.

ydkjs-2.png

Recent Features

  • 9 More Mind-Blowing WebGL Demos

    With Firefox OS, asm.js, and the push for browser performance improvements, canvas and WebGL technologies are opening a world of possibilities.  I featured 9 Mind-Blowing Canvas Demos and then took it up a level with 9 Mind-Blowing WebGL...

  • Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the...

  • Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else?...

Incredible Demos

  • CSS :target

    One interesting CSS pseudo selector is :target.  The target pseudo selector provides styling capabilities for an element whose ID matches the window location's hash.  Let's have a quick look at how the CSS target pseudo selector works! The HTML Assume there are...

  • MooTools CountDown Plugin

    There are numerous websites around the internet, RapidShare for example, that make you wait an allotted amount of time before presenting you with your reward. Using MooTools, I've created a CountDown plugin that allows you to easily implement a...

  • jQuery Countdown Plugin

    You've probably been to sites like RapidShare and MegaUpload that allow you to download files but make you wait a specified number of seconds before giving you the download link. I've created a similar script but my script allows...

Discussion

  1. 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/

    • 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

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

    • nev

      Yes but you could employ logic in both cases which does and does not find the string “iPad”.

  3. Rob

    Great! Now I can redirect/block iPad users!

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

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

  6. 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";
    }

    • 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: that is in a javascript

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

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

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

  12. maybe

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

  13. 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 ''; }
    ?>
    
    • Easy to do redirecting in PHP:

      If you just want to redirect iPhone users:

      If you also want to bounce iPad users, use this instead:

      Here’s what the session variable “fullsite” is for:

      I always use a link in the mobile site that would allow the user to go to the full site if he wishes; the link goes to a page I call “fullsite.php,” and which includes this code:

      This sets the session variable and then sends them back to the full site’s home page, and prevents the PHP from bouncing them continually back into the mobile site.

      Note that the session variable will stay set until they close their browser.

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

  20. Morten Skogly

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

  21. “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”

  22. 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!

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

  24. Awesome tutorial! Saved me for iPad in my use

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

  26. thank you for info

  27. 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)

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

    • 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

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

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

  28. Frank

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

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

  30. Hopefully the code will work now

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

  32. 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…

  33. Efrenk

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

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

  35. 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”…

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

  37. How about for ipad 2?

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

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

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

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

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

  43. Genesis

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

  44. This post is missing what’s by far the best check for an iPad (or iPhone) in JavaScript:

    navigator.platform === 'iPad' || navigator.platform === 'iPhone'

    The best part is that the platform property can’t be easily spoofed. Some Android devices, for example, will allow users to change the user agent string to match that of an iPad, but changing it won’t affect the value of navigator.platform.

  45. [...] David Walsh Blog – iPad Detection Using JavaScript or PHP [...]

  46. [...] the same way as you’ve always done and let iPad people pinch and zoom to navigate around them.iPad detection using PHP and JavaScript to redirect the user to a different iPad only design.Make a website [...]

  47. [...] 戴维•沃尔什(David Walsh)在他博客上就iPad及iPhone上的浏览器检测方法提供了非常不错的示例。其中提供了PHP和JavaScript两种检测方式。 [...]

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

  49. [...] 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. [...]

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

  51. [...] iPad Detection Använda JavaScript eller PHP [...]

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

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

  54. [...] is a solution using javascript. But I prefer PHP. Because some user prefer to disable javascript in their browser. Less people do [...]

  55. [...] 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. [...]

  56. […] iPad Detection Using JavaScript or PHP These code snippets will help you to redirect iPad users to a different version of your website or to implement different styles to your standard website if your user is surfing on an iPad. […]

  57. […] Detection David Walsh provides good examples of proper browser detection for the iPad and for the iPhone on his blog. Options for PHP and Javascript are […]

  58. […] 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. […]

  59. I advise you check out http://wurfl.io/

    In a nutshell, if you import a tiny JS file:

        <script type='text/javascript' src="//wurfl.io/wurfl.js"></script>
    

    you will be left with a JSON object that looks like:

        {
         "complete_device_name":"Google Nexus 7",
         "is_mobile":true,
         "form_factor":"Tablet"
        }
    

    (that’s assuming you are using a Nexus 7, of course) and you will be able to do things like:

    if(WURFL.form_factor == “Tablet”){
    //dostuff();
    }

    The service also goes out of its way to detect specific iPad models.

  60. […] Source: David Walsh […]

  61. […] Source: David Walsh […]

  62. […] iPad Detection Using JavaScript or PHPThe 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. […]

  63. […] Detection David Walsh provides good examples of proper browser detection for the iPad and for the iPhone on his blog. Options for PHP and Javascript are […]

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Use Code Editor