Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

iPhone & iPod Detection Using JavaScript

39 Responses »

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?

Discussion

  1. February 19, 2009 @ 9:38 am

    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. February 19, 2009 @ 10:22 am

    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.

  3. February 19, 2009 @ 10:54 am

    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. February 19, 2009 @ 10:59 am

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

  5. February 19, 2009 @ 11:24 am

    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. February 19, 2009 @ 11:25 am

    Oh, btw good script to have at your disposal.

  7. February 19, 2009 @ 10:30 pm

    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. February 19, 2009 @ 11:19 pm

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

  9. February 20, 2009 @ 1:53 am

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

  10. gareth
    March 4, 2009 @ 11:22 am

    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

  11. tim
    May 2, 2009 @ 3:55 pm

    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. May 24, 2009 @ 9:24 pm

    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. jared
    August 26, 2009 @ 7:02 pm

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

  14. September 2, 2009 @ 5:29 am

    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. October 22, 2009 @ 6:01 am

    thanks, I’ve been looking exactly for this!

  16. jaime
    November 4, 2009 @ 2:32 pm

    @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. hwkd65
    November 18, 2009 @ 12:47 pm

    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. danny
    November 25, 2009 @ 7:20 pm

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

  19. November 25, 2009 @ 7:23 pm

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

  20. December 8, 2009 @ 5:59 pm

    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. December 8, 2009 @ 6:02 pm

    (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 @ 4:05 pm

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

  23. craig
    February 11, 2010 @ 11:36 am

    @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. March 2, 2010 @ 8:52 am

    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 @ 1:00 pm

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

  26. April 27, 2010 @ 9:57 pm

    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 @ 10:01 am

    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 @ 10:03 pm

    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. May 27, 2010 @ 4:11 pm

    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. May 28, 2010 @ 1:47 am

    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. May 28, 2010 @ 1:49 am

    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

  32. May 28, 2010 @ 1:50 am

    right ok go here for code:

    http://www.mgpwr.co.uk/code.txt

  33. May 28, 2010 @ 5:11 am

    @Paul Chinetti:

    I got the same error when i spelled the directory wrong

  34. May 28, 2010 @ 9:36 am

    @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?

  35. ant gray
    June 2, 2010 @ 4:46 pm

    PHP detection is better. No useless code for other browsers

  36. June 19, 2010 @ 4:08 am

    @Mark Petherbridge

    Works like a complete charm, great work!

    Thanks.

  37. June 20, 2010 @ 3:36 pm

    @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:

  38. July 29, 2010 @ 2:48 pm

    This is some interesting coding :)
    Thanks a lot.

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

    Thanks again.

  39. jonathan
    August 8, 2010 @ 8:33 pm

    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.

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!