iPhone & iPod Detection Using JavaScript

Written by David Walsh on February 19, 2009 · 88 Comments

I was browsing the ESPN.com source code recently and stumbled upon their method of detecting iPhone / iPod touch users and redirecting them to their iPhone-compatible website.

The JavaScript

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
	 if (document.cookie.indexOf("iphone_redirect=false") == -1) window.location = "http://m.espn.go.com/wireless/?iphone&i=COMR";
}

The code itself is short and sweet. I, however, would prefer using the server-side method of user agent checking.

The PHP

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

Which would you prefer?

Comments

  1. Thank you so much for this post. I have a couple sites I would love to test this on to see if there is much if any difference between the two.

  2. Before everyone goes crazy implementing things like this, they should realize that some users do not want to be forced to use the mobile version. For example, I found it to be impossible to change my fantasy football lineup on ESPN.com from the iPod Touch because it kept redirecting me to their stripped-down mobile version of the site. There at least needs to be a way to override the redirection if the user so chooses.

    • Brandon Crooks November 8, 2011

      I agree. Sometimes the water’ed down version of a site dramatically reduces usability. I’m pretty sure you can implement a link to redirect to a page without mobile redirection.

  3. I’d prefer a mobile stylesheet, but these are definitely keeper snippets. Thanks, David!

    @Jeremy:
    It would be a horrible practice not to have a big link to the non-mobile version of the site, which had better have a way to detect that such a link was clicked. I’m sure people that read this know that, right?

  4. @Jeremy Parrish: Good point. I’m currently working on a mobile website and that’s one consideration I’ve taken.

  5. iPhone and the iPod touch are perfectly capable of rendering a website in full version and navigation is not a problem. I would prefer to have an option/link to go to a mobile site.

  6. Oh, btw good script to have at your disposal.

  7. Just in case anyone is interested, we had an excellent article on Dev-Tips by Brian Cray that explained how to redirect iPhone and blackberry users using .htaccess. You can find it here: http://dev-tips.com/featured/redirect-iphone-blackberry-palm-requests-with-htaccess

    Excellent article and scripting as always David.

  8. Awesome tip Drew! Your tutorial has all of the rewrite rules commented out though — you may want to change that. Thanks for commenting!

  9. Whoops, thanks for the heads up David, must have missed that when I was publishing the article. Much thanks :)

  10. Gareth March 4, 2009

    Good script, been looking for something like this.
    I have another iPhone question:

    Is there a way of getting access to the location data (lat,lng) of the iPhone using PHP, or some other lang?
    e.g: User browses to website using safari, clicks on a button that send their lat,lng to the website.
    It is implemented on many of the apps that can be installed on the iPhone (twitterfon for example), but I’m trying to get it working on a website.
    Cheers
    Gareth

    • i also have a question related to iphone,The thing is i am working on a desktop application of java and i want to detect the device connected to my system and check whetehr it is iphone,or ipod or any other device.so can u please help me.

  11. I looked all over for code that worked for me. This was perfect
    (I have a flash-based site that can’t be viewed by most phones)
    However, on the mobile-centric site, I have a link to the flash site without the sniffer — which I find as an acceptable work-around to the person that was having trouble with ESPN re-directing his fantasy football site.

    Thanks so much!

  12. Thank you so much for this post. I was looking for a simple javascript method of sniffing for an iphone and re-directing to a separate page of content. This worked the first time! Thank you so much for posting this.

    Grateful.

  13. this is great for all-flash sites…iphones can NOT render those at all. That’s exactly what i need it for, thanks!

  14. Hi David, the javascript works great. Just wondering if you got anywhere in writing that ‘view the full site here’ code? I’ve had a look around, but i think its going to need cookies and things I will just never get to grips with. Any ideas would be great!

    thanks,
    James

  15. thanks, I’ve been looking exactly for this!

  16. @Mark Sanborn: Not true if the website is all in Flash! This script is perfect to redirect to a HTML version of the same website. Thanks for the script. Hope some day soon Iphones can run Flash.

  17. got the javascript to work then all of the sudden it stopped working

    this .php version and all of the others have not worked

    .htaccess options have also not worked

    i am going to tell client to go .mobi

    need to show home page w/o flash gallery

  18. wouldnt using one of the web services like handsetdetection.com be a more effective way?

  19. @danny: This script is obviously very primitive. I’d prefer not to rely on another service if I didn’t have to.

  20. Yes, you can use JavaScript to get the location data like so:

    navigator.geolocation.getCurrentPosition( locationIs, locationNotSUpported );

    function locationIs(loc)
    {
    // use the values
    // loc.coords.latitude;
    // loc.coords.longitude;
    }
    function noLocation()
    {
    //fallback code if no location handling
    }

  21. (That last reply of mine was aimed @Gareth in response to his question as to whether you could get the geo information from an iPhone in a web app.)

  22. Chad Palmer January 26, 2010

    @Mark Sanborn: Especially if they are flash based, right?

  23. @Mark Sanborn: I put the redirection on index.html and if iPhone I goto iphonehome.html else home.html
    And then I put a link on the bottom of the iphonehome.html to link to home.html. Since home.html doesn’t have the javascript redirector they stay there. Works for me…

  24. You should note that using strstr to find if a particular string is inside another is not recommended, and that the function strpos should be used instead.

    http://php.net/strstr

  25. Corey M April 14, 2010

    I think is great for flash only websites who create another website specially for mobile users :)

  26. Hi,

    Thx for the information as it’s something I’ve always been curious about.

    I get the iPhone detection, but I wonder if anyone has a good lead or solution on just a very simple (HTML) or dynamic (jQuery/JS) iPhone/mobile site that can reference an image pre-existent on a flash-based site with deep linking and unique urls?

    To clarify, I’m a photographer who’s site has each image file at a unique URL. Each images lives in that gallery’s folder on my server, so when visiting my flash-based site my images aren’t locked in a shockwave or movie file on account of a backend CMS so I can add/subtract imagery.

    Any and all help, thoughts or suggestions are greatly appreciated.

    Mike

  27. William Murray May 4, 2010

    David thank you very much for this information. Some what new to this stuff where would you put this in your flash page? Thank you for the help

  28. Paul Chinetti May 4, 2010

    Cannot Open Page
    “Safari cannot open the page because too many redirects occurred.”

    On the iPhone it flashes the correct address in the address bar, then that error pops up on the screen.

    Any suggestions?

  29. Great thank you for the post!
    Is there any way to creat a “full site” – link on the mobile site without it redirectin back to the mobile site again?

  30. Thats something I would like to know also Victor Reyes, maybe something like a url variable specifier would work..

    for example when you click Full Site the url link will be http://www.yoursite.com?mobile=no
    then use the $_GET to remove the php like…

    try that, quick run up :S

    follow me @mgpwr

  31. Thats something I would like to know also Victor Reyes, maybe something like a url variable specifier would work..

    for example when you click Full Site the url link will be http://www.yoursite.com?mobile=no
    then use the $_GET to remove the php like…

    [code]

    [/code]
    try that, quick run up :S

    follow me @mgpwr

    • That’s exactly what i need but for the JavaScript redirect. Any ideas?

  32. @Paul Chinetti:

    I got the same error when i spelled the directory wrong

  33. @Mark Petherbridge:

    Thanks for the code, im yet to try it. But as far as i see would that technique mean that i have to rebuilt all the links on full site to ?mobile=no?

  34. Ant Gray June 2, 2010

    PHP detection is better. No useless code for other browsers

  35. @Mark Petherbridge

    Works like a complete charm, great work!

    Thanks.

  36. @Victor Reyes: You would need another $_GET function to detect that – thats what i did because i was rushing however i see no problem with reversing the script to detect when its a browser instead of an iPhone – this seems pretty cool: http://drupal.org/node/65903 for a website HOWEVER i would advise a caution because if u dnt list all browsers then it will not work..

    Im gunna be working on my site a little with this in mind – DM on twitter @mgpwr or contact me through my website http://www.mgpwr.co.uk and ill send ya code when its done….

    @Victor Reyes:

  37. This is some interesting coding :)
    Thanks a lot.

    I’m currently developing my website and it does need iDevice support!

    Thanks again.

  38. Jonathan August 8, 2010

    Do you know if this script is good to use with other agents or are the Android and iPhones the only smart phones with browsers that read JavaScript? I found another method that covered all phones/agents, but was totally over my head, and I’m not on an Apache server. This code works great and I am so greatful for your post. Thank you.

  39. Nice code! Thank you!

  40. Victor, that’s something I’m looking for as well. I am using the JavaScript redirect, (and am a total Noob), but and wondering if you could use a variable to ignore the script, as in “if the source is “examplelink” on “mobile.my site.com” then ignore the JavaScript redirect”.

    Would using something like ?utm_source help?

  41. Thank you so much THANK YOU
    I love you so much
    Thnaks

  42. The above JS snippet is perfect for me . Yet reading through the comments above, I wonder if just using a secondary CSS for mobile devices would be better.

    On my site I have iFrames for image scrolling. Thanks to web-kit you have to use two fingers to scroll, and it’s pretty jumpy at that. I was thinking about just putting a JS to detect mobile devices as above to do a document write to use two fingers but that is messy isn’t it?

    So what is best, a second site where I have a second CSS, and either get rid of the iFrames and replace them with normal divs, or is it to just have a mobile CSS to run on the current site?

  43. Great article! I wrote a similar article which covers Mobile Browser Detection and Redirection with Perl (http://www.mlynn.org/2010/07/mobile-device-detection-and-redirection-with-perl-and-cgi/) and PHP (http://www.mlynn.org/2010/06/mobile-device-detection-and-redirection-with-php/) The articles have downloadable example scripts as well as a test implementation at http://www.mlynn.org/uatest

    Enjoy!
    Mike

  44. Gibatronic January 25, 2011

    the code can be even simplier:

    if (/iPhone|iPod/i.test(navigator.userAgent)) {
    // HELL YES! WE GOT AN IPHONE OR IPOD HERE!
    }

  45. I prefer JavaScript because I don’t think my free webhost supports PHP. Thanks for the code!

  46. Thanks man but PHP is far better

  47. Thank you for the tip!
    I used the Javascript one and it work great! I was searching for about an hour to figure it out and POW! I found your site and it work on the first try.
    Good job! :)

  48. thanks david. you saved me… greats from izmir,turkey ;)

  49. I’m having a bit of trouble with this. I put the code in the head of my main website (the desktop version). And went into the CP of my hosting provider and created a subdomain (the domain for the web version). I directed it to look into a specific folder for the files and when I go to the url it redirects me like it should to the web version but all the css, javascript, images (basically any links) have been stripped and don’t work/appear at all.

    Anyone have any ideas?

  50. indeed PHP is much better for user-agents detect… avoiding redirects or links altering.. like mobile.domain.com .. or domain.com/mobile .

    But as @Omari said .. or for those who do not use/have PHP available .. or any other serverside, javascript is a good idea.

    Also .. to be helpfull here are some other mobile extentions that would help.

    match(/android/i)
    match(/opera mini/i)
    match(/blackberry/i)
    match(/(pre\/|palm os|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)/i)
    match(/(iris|3g_t|windows ce|opera mobi|windows ce; smartphone;|windows ce; iemobile)/i')

    also .. for PHP .. use preg_match instead of strstr … is faster

  51. This method works great – I use it for http://www.digisolved.com and it works great!

  52. Wow! It works perfectly!

  53. Hello David,

    why in all mobile site their domain starts with “m” like m.mysite.com is that only a subdomain or once the site run in mobile phones the “m” will automatically replace the www.

    Thanks

  54. I prefer css media, but this snippet help me to much for hiding toolbar in IOS, and not in the browsers users, preventing the user lose the point of the site when refreshing or sending a form.

    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { //if IOS do this things:
    window.addEventListener(‘load’, function() {
    setTimeout(scrollTo, 0, 0, 1);
    }, false);
    }

  55. I prefer css media, but this snippet help me to much for hiding toolbar in IOS, and not in the browsers users, preventing the user lose the point of the site when refreshing or sending a form.


    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { //if IOS do this things:
    window.addEventListener('load', function() {
    setTimeout(scrollTo, 0, 0, 1);
    }, false);
    }

  56. Thanks a million. It took me two days just to find this fix. :o)

  57. I’ve searched for hours for different ways of detecting browsers:
    As a designer with limited knowledge of javascript and php, this has been the only example I’ve found that makes sense and actually works. Thank you for your rare ability to explain code that i now understand and actually works for me. (I dont care if php is better, I cant get it to work and is therefore useless to me, if you want to get high and mighty, with php, write an understandable tutorial and then maybe non geeks will use it)

  58. Hey, i found to http://tinytop.mobi best detector real user agent script in the world. Awsome isn’it? :o

  59. I’m still a bit new with all this.

    Which .php file would one place the .php version of this code? PhPinfo.php?

  60. For most changes, I think just detecting the screen width and swapping out styles accordingly will do what you want. After all, what you’re mostly concerned about is simplifying your page for a smaller screen. Browser sniffing has been a bad idea since 1998 and the same reasons apply now to mobile that applied then, and will lead to the same response – browsers spoofing the user agent string.

  61. inactivist May 29, 2012

    One good reason to do this in JavaScript rather than on the server: caching. If you’re caching pages, you really don’t want to do this in PHP (or other server script).

  62. I use this to redirect to site A if on iPad/iPhone but to site B of on a other divice:

    if(
    ((navigator.userAgent.match(/iPhone/i)) ||
    (navigator.userAgent.match(/iPod/i))) &&
    document.cookie.indexOf(“iphone_redirect=false”) == -1
    )
    {
    window.location = “http://site_a.com”;
    }
    else
    {
    window.location = “http://site_b.com”;
    }

  63. Detect all possible browsers like: proxies, desktops, tablets, mobiles and applications (java, symbian, android). This is the best code ever, enjoy ;) http://code.google.com/p/detect-real-user-agent/

  64. i want to restore my backup data from mobile to pc
    so i need to know what is the java code for that using USB device.
    Can anyone tell me..

  65. hello everybody!
    I use this code to redirect mobile user from full site to mobile version:

    //

    My question is how to use this code to do the same thing in the other direction. I explain: i want to prevent people to pick up my jquery mobile source code by redirecting user from mobile “m.pixart.ma” version to full version “pixart.ma” if they try to open it on desktop browser.
    Thank you.

  66. also have a question related to iphone,The thing is i am working on a desktop application of java and i want to detect the device connected to my system and check whetehr it is iphone,or ipod or any other device.so can u please help me.

  67. if(navigator.userAgent.match(/iPhone|iPod/i))

  68. hey if you browse with Opera you can tell the website you want to see the desktop version.

  69. [...] Source: davidwalsh.name/detect-iphone [...]

  70. hello, I have an application developed in JQueryMobile and I need to make an application for IPhone to redirect to my URL.
    Can someone give me a hand?
    I could easily do to Android and now I have to do for iPhone.
    What better way.
    Thankful number attention.

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

  72. Hi, I there a reason you separate it out into different match statements rather than the one regex, such as

    navigator.userAgent.match(/iPhone|iPod/i);

    This statement will allow you to add on more mobile browsers such as android and opera mini without creating a big mess of or conditions, and is probably faster to just do one match. However, on my code I’ve noticed some other js on iphone acting strangely with this change, yet to determine if it is cause by an unseen js error on the iphone or if it was caused by an unrelated issue.

  73. John Nessim August 1, 2013

    Thank you very much. Worked like a charm.

  74. John Nessim August 2, 2013

    I added the following part to the condition and it worked perefectly with the iPad.

    || (navigator.userAgent.match(/iPad/i))

    Thanks again! :)

  75. Please I need the one that can work even for Blackberry phones.

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

  77. This script will tell you if a device is an iPhone, but it won’t tell you what actual device it is. For example, iOS 7 will run on iPhone 4 through 5 and 5S. For those who care, WURFL.js fixes that:

    http://wurfljs.com/

    disclosure: I work for the company that provides this, but since it’s a free service, I still think it deserves mentioning here/ Thank you.

Be Heard

Tip: Wrap your code in <pre> tags or link to a GitHub Gist!

Use Code Editor
Older
Script & Style Revamp with Submission Favelet
Newer
Book Review: PHP5 CMS Framework Development