How do I detect an iPhone user coming to my site?

Amazon.com’s jumped on the wagon, and Meebo has too: they automatically give you a different version of their site if you’re browsing from an Apple iPhone. I want to do that too. How the heck do I detect that a visitor has an iPhone?

The key to detecting a browser type is to remember that there’s an environment full of information transmitted with each query sent from the web browser to the server. It includes the obvious things like the requested data file (which can be an HTML document, GIF or JPEG image, AVI movie, FLV animation or related) and the IP address of the browser’s computer, but it also includes a critical variable called HTTP_USER_AGENT.
Visit with a regular browser from a regular computer and you’ll see something like this:

HTTP_USER_AGENT=Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)

Here you can see that I’m testing from Firefox (which identifies itself as Mozilla for historical reasons) running on Windows XP (though it’s identifying it as Windows NT for some cockamainie reason) and that I’m also running .NET.
Grab that same environment value from a slick Apple iPhone query, though, and the values are quite a bit different:

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

Pretty interesting reading if you’re a geek: You can see where it’s also identifying itself as Mozilla, but this time as Mozilla/5.0 rather than Mozilla/4.0. The string “iPhone” appears, which is what we’ll key on, but notice also that it says that it’s on a system with a “CPU like Mac OS X”, just as we iPhone users have been suspecting for a while.
You can see the basic test we’ll need to do here to ascertain if the visitor is using an iPhone or not: if their HTTP_USER_AGENT environment value contains the string “iPhone”, we’ve got a match. Otherwise it’s something else on some other device or computer.
You can do this test and act on it in a zillion different places, ranging from the actual Web server ruleset to JavaScript code to PHP conditional code to even having a separate “gateway” script page that everyone hits and redirects them to the iPhone or non-iPhone version of your Web page and site.
A JavaScript snippet might look like this:

var agent=navigator.userAgent.toLowerCase();
var is_iphone = ((agent.indexOf(‘iphone’)!=-1);
if (is_iphone) { conditional code goes here }

Rather do it as a shell script? Me too. Here’s how I’d do that as a rudimentary Linux shell script:

#!/bin/sh

if [ ! -z “$(echo $HTTP_USER_AGENT | grep iPhone)” ] ; then
  echo “Location: iphone/index.html”
else
  echo “Location: index2.html”
fi
exit 0

You can also have the conditional directly in CSS itself, if you’re really into cryptic notations:

<!–#if expr=”(${HTTP_USER_AGENT} = /iPhone/)”–>
<style type=”text/css”>
<!–
here’s where you’d include special styles for the iPhone
–>
</style>
<!–#else –>
<style type=”text/css”>
<!–
regular web browser style and CSS information goes here
–>
</style>
<!–#endif –>

The basic idea in either case is that once you have detected that they’re running an iPhone, you can modify what you deliver to them, either changing what’s on the page, perhaps giving them a completely different version of the page, or even taking them to a different site entirely.
Hope that helps you out! Don’t forget while you’re here that I have quite a lot of iPhone help here too.

44 thoughts on “How do I detect an iPhone user coming to my site?”

  1. I think the USER_AGENT has changed to:
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2
    which no longer has the “iPhone” string in it – so your suggestion now fails. Do you have a recommendation on how to detect it now?
    Maybe check for both “Mozilla” and “Gecko” and “Chrome” and “Safari” all present? It sure would be nice if they would just standardize it and mention “mobile” or put “iphone” back in…
    Thanks, Dave!

    Reply
  2. <script language=javascript>
    <!–
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
    {
    location.replace(“iphone-version.html”);
    }
    –>
    </script>
    Will this work for Ipad? Thanks!!

    Reply
  3. hi dave,
    i’m a c# programmer i’m developing Mobile Application Builder once the user selected template for his site i have to show how its looks in iphone Exactly, i searched for simulator which can embed with the My webpage as part of the Application but i couldn’t get it ,i got only some simulators which is directly testing in their site ,so please help to find some iphone simulators which can embed and able to show preview in my site.
    thanks in advance,
    chandru.v

    Reply
  4. I put this at the beginning of my index.php:
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
    {
    var qes = confirm( “I have a site made for the iPhone. Click OK to visit it, or Cancel to go to the normal site.” );
    if ( qes )
    location.replace(“http://iphone-url/”);
    }
    Works as intended … but as my site is bilingual, I’d like to have this dialogue bilingual too … could I extend the script to detect the iPhone system language and put out the text accordingly? As in: if german, say “Hallo”, else say: “Hello” …

    Reply
  5. here a other solution, all iPhone is javascript enable 🙂
    –script–if (navigator.userAgent.toLowerCase().indexOf(‘iphone’)!=-1) document.documentElement.className+=’ iphone’; –/script–

    Reply
  6. Jules, many browsers now let you specify what browser you want to masquerade, but that’s not going to help you on your iPad. Even if you could spoof it, Google Docs just plain won’t work on the iPad within the browser. Search the iPad App Store, however, there are some third party solutions that give you access…
    Michel, similarly, you should check that your browser isn’t set to report it’s a different program. Many browsers have a “Debug” menu, for example. Also look in the dusty corners of Preferences.

    Reply
  7. I am using a desktop but some site would notify that I am using a mobile browser and would prompt me to view the page in a mobile browser or a desktop browser.
    Is it possible that my computer is hacked by some tech savvy voyeur?

    Reply
  8. Ok I have the reverse question. What if I want to spoof my http user agent?
    Google docs will not let me edit my site from my iPad. Apple store peeps say it’s google blocking the iPad. Can I tack something on to my address to make google think I am using ie on a pc?

    Reply
  9. i am currently using for my website is
    this is currently what i am using on PcsSite.Net it works great and i made that my self lol, well thank you a lot and i thought i share this little peice of code to you all
    \\ read browser settings
    $agent = $_SERVER[‘HTTP_USER_AGENT’];
    \\ Browser settings found we need to find what type of browser it is so we move on to finding device name
    \\ if iPhone is found we include a page for the iPhone browser
    if (eregi(“iPhone”, $agent)) {
    include(“iphone.php”);
    }
    \\ if Blackberry is found we include a page for the Blackberry browser
    elseif (eregi(“BlackBerry”, $agent)) {
    include(“blackberry.php”);
    }
    \\ if not a mobile browser we include our index page
    else {
    include(“index.php”);
    }
    thank you a lot and have a great day everyone and i hope this helps you in the near future

    Reply
  10. How do you detect the “white” shift key caps lock from the “blue” shift key caps lock for the iPhone? My detect caps lock JavaScript is flagging the white key and throwing up the warning prompt that’s supposed to be for when the caps lock key is enabled on a desktop.

    Reply
  11. I have a question about the other end- I want to hide the fact that I’m browsing on an iPhone. I want the website to believe that I am running on a PC so that I am never redirected, because I’m running a computer, I don’t want to go to a watered-down version of the site.
    Do you know a way of hiding the iPhone information? I am not opposed to jailbreaking.
    Thanks.

    Reply
  12. The right way to do it with some js is actually :
    if(/iphone/i.test(navigator.userAgent)){ /*Execution here*/ }
    You would rather use the test() method than the match() one.
    The i flag is for case insensitive regular expression so don’t bother with some useless toLowerString().
    That’s right, you only need a single line of code ^

    Reply
  13. How is everyone thinking? I believe everyone except one commenter just ignored the iPod Touch, you do understand its browser is exactly like the iPhone’s, right?
    <?php
    if (preg_match(“/iP(hone|od)/i”, $_SERVER[‘HTTP_USER_AGENT’])) {
        // User has an iPhone/iPod
    } else {
        // User has something else
    }
    ?>

    Reply
  14. To load a different style sheet for iphone rather than redirect, use this in php:
    <link rel=”stylesheet” type=”text/css” href=”<?php if (stristr($_SERVER[‘HTTP_USER_AGENT’], ‘iphone’)){echo ‘iphone.css’;} else{ echo ‘default.css’;}?>” />

    Reply
  15. For the love of God, stop redirecting users. No one with an iPhone wants to look at a crappy mobile web site. If you must do this, please do the following:
    1. Take us to the same page we were trying to reach, not the home page of your iPhone site; and
    2. Give us a link to the full version so we have a choice.
    Just know that when you redirect us, we end up going to the google caches version of the page we were trying to reach.

    Reply
  16. How do I make a conditional statement that hides the contents of the tag from iPhone and iPod Touch users?
    If iPhone or iPod Touch, hide xyz. xyz is not a div, but rather a few script tags, so I don’t believe it would not work with css.
    Thanks in advance.

    Reply
  17. holy cow, that’s a work of genius, after hours spent trying to kludge position:fixed to work I can just go round it and present an iphone optimized version for my client as well as the scrolling desktop version.
    absolutely brilliant. thankyou.

    Reply
  18. Heya, is there any information about to see other phones such as Nokia ? i.e so i can make a custom website for nokia phones too ??
    feel free to email me.
    thankyou in advance.

    Reply
  19. Dear Dave
    I’ve made a Drupal web site, and I wish use Jquery to reveal iPhone. Is there a way to reveal iPhone by jquery?
    I’ve reveal the safari browser woth this code:
    if ($.browser.safari) {
    alert(“se hai l’iPhone Aggiungi alla Home questo sito”);
    }
    BUt I can’t understand if the safari browser is for iPhone or Mac…
    Someone can help me please?

    Reply
  20. you can also use a more advanced web service such as handsetdetection.com which returns real time information on which devices are accessing your site – and then allowing you to adjust the view. Data it returns includes screensize, browser, phone make and model and also location based information.

    Reply
  21. I have created a website using iWeb. I would like to insert some html code (or some type of code) that recognizes when a viewer is visiting on an iPhone versus a regular computer. I’ve read the above and tried inserting the java script in the html snippet but it does not work. Do you know if there is a way to do this?
    Thanks,
    Tom Fawbush

    Reply
  22. <script language=javascript>
    <!–
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
    {
    location.replace(“iphone-version.html”);
    }
    –>
    </script>

    Reply
  23. Michael –
    I think you need to use window.location for your redirect:
    var agent=navigator.userAgent.toLowerCase();
    var is_iphone = (agent.indexOf(‘iphone’)!=-1);
    if (is_iphone) { window.location =”http://www.qualitycontactsolutions.com/iphone/” }

    Reply
  24. Hello,
    I am trying to implement your javascript into my site for a page redirection when the user visits the site with a Iphone but i am experiencing problems i was hoping that you could help me by telling me what i did wrong for the javascript coding.
    var agent=navigator.userAgent.toLowerCase();
    var is_iphone = (agent.indexOf(‘iphone’)!=-1);
    if (is_iphone) { scr=”http://www.qualitycontactsolutions.com/iphone/” }

    Reply
  25. Hey Guys,
    The javascript in his post is a bit broken, here is the fixed code:
    var agent=navigator.userAgent.toLowerCase();
    var is_iphone = (agent.indexOf(‘iphone’)!=-1);
    if (is_iphone) { /* execution here */ }

    Reply
  26. Hi
    I am developing site for small browsers.Currrently i am facing issue for Iphone and Blackjack.On this i am gettting large browsers screens .I am detecting iphone browser through user-agent but since i dont have iphone i thought of checking it on simulator which gives me information of IE.
    also i would like to know how to detect visitior coming from blackjack.

    Reply
  27. Ruby on rails has auto detection for various types of request:
    respond_to do |format|
    format.html #index.html.erb
    format.xml { render :xml => @articles.to_xml }
    format.rss { render :layout => false } #index.rss.builder
    format.iphone do #action.iphone.erb
    render :layout => false
    end
    end

    Reply
  28. Dave,
    Thank you for this info.
    I have been trying to use the Javascript you listed here to redirect iphone users to a different version of a site, with no luck.
    How would you do it if you had to use javascript?

    Reply
  29. var agent=navigator.userAgent.toLowerCase();
    var is_iphone = ((agent.indexOf(‘iPhone’)!=-1);
    if (is_iphone) { conditional code goes here }
    I think you might want to do indexOf(‘iphone’) since agent is all lower case.

    Reply

Leave a Comment

Receive My Weekly Email Newsletter:

Your email address:*
First Name
Please enter all required fields Click to hide
Correct invalid entries Click to hide

Recent Posts

On My YouTube Channel

Date Archives