Android Detection with JavaScript or PHP

By  on  

I've noticed that two of my blog posts continue to get more popular each week:  iPad Detection with JavaScript or PHP and iPhone and iPad detection with JavaScript or PHP. What's obvious is that Android development is a hot topic that will only grow.  Here are a few methods by which you can detect iOS' main competitor:  Android.

The JavaScript

Searching the user agent string for "Android" is the quickest method:

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
	// Do something!
	// Redirect to Android-site?
	window.location = 'http://android.davidwalsh.name';
}

The PHP

Again, we'll use PHP's strstr function to search for Android in the user agent:

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
	header('Location: http://android.davidwalsh.name');
	exit();
}

Bonus!  .htaccess Detection

We can even use .htaccess directives to detect and react to Android devices!

RewriteCond %{HTTP_USER_AGENT} ^.*Android.*$
RewriteRule ^(.*)$ http://android.davidwalsh.name [R=301]

And there you have it:  three different Android device detection!  Have fun with your mobile development!

Recent Features

  • By
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

Incredible Demos

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

  • By
    Scroll IFRAMEs on iOS

    For the longest time, developers were frustrated by elements with overflow not being scrollable within the page of iOS Safari.  For my blog it was particularly frustrating because I display my demos in sandboxed IFRAMEs on top of the article itself, so as to not affect my site's...

Discussion

  1. Erik Edgren

    Very neat solution! :D I love the detection via .htaccess. Thanks a lot!

  2. Blaine

    Depending on how you have your site setup, you may also want to detect that it’s not already at the android address.

    Would be useful if you are just theme switching, instead of going to a completely different website.

  3. Very nice. However, the PHP solution is slightly flawed. Strstr() returns the position at which the “needle” was found, or boolean false if it’s not found at all. If “Android” was found at the very beginning of the string, it would return 0, which evaluates to false. This is obviously incorrect. The solution is to make a typed check.

    if(strstr($_SERVER['HTTP_USER_AGENT'],'Android') !== false) {

    Also, it might be a good idea to use stristr(), for case insensitivity.

    • Nice tip. However, you might wanna use stripos() since it’s faster.

    • Updated guys. Android never appears at the beginning of the UA strings, but it’s good to keep good practices.

  4. Absolutely fantastic, David! Keep up with the good work. Thank you for sharing!

  5. Very nice article!

    For a detailed detection with php check out the tera-wurfl project.
    I’m using it in my projects to detect all mobile devices.

  6. There are a lot of people who are against user agent detection (preferring something more universal such as window size detection with CSS media queries, for example).

    However, I think there’s still a place for it if you architect your site properly. You’re never going to detect the string “Android” in a non-Android device, for example.

    As long as there’s a fallback for when no “sure-fire” match is made, I don’t see why we can’t add UA detection as an enhancement to our sites, as long as we ensure no false positives and that the experience isn’t broken by detecting UA.

    (also worth noting: people should always have the option to switch to “full/standard” website; if they feel like swiping and zooming around, let them!)

    • fabsn182

      Nice post but why should you deliver an android optimized page for somebody using an android tablet with a screen size just like the iPad?

    • Daniel

      One example: you want to showcase a store button for Google Play to your Android users, and not show an iTunes button.

  7. Robert

    I agree with Andi. The Tera-WURFL project is the way to go. the amount of detail you can get from each device is simply amazing. so much more than user agents and window size, but playback capabilities, versions, etc.

  8. fabsn182

    Nice but I think you shouldn’t use browser but feature detection. It might be possible that users won’t use the android stock browser and also change the user agent to iPhone/iPad or desktop PC (Firefox or IE).

    • I’m open to suggestions for feature detection on the client side. What would you recommend?

  9. User agent sniffing must die. Nice job advocating this bad practice.

    • Thank you so much Mathias!

    • If you don’t want people to know your user agent, then don’t tell them your user agent. That’s like complaining about davidwalsh.com publishing the comment you just willfully posted.

  10. Android’s dev blog points out that simply looking for “Android” in the UA might cause you to serve a mobile version of the site to a large-form-factor Android device.

  11. Bad

    When will if(isAndroid) evaluate to true in your examples?

    Almost always (-1 anyone?)!! Badly implemented bad practice!

  12. Awesome…Very helpful..thanks

  13. Top Stuff David. As an aside, you can use a service like http://www.handsetdetection.com to do Android detection as well. Handset Detection can also tell the difference between tablets & handsets – which can be handy for redirection. (disclaimer : I work there).

    To allow visitors to go from your mobile site back to your standard site check the http_referrer. If the referrer is your mobile site then disable the check. :-)

  14. Thanks for sharing! Just what I needed :-)

  15. Simple solution

  16. Bryce

    Thanks for the code! What those ‘bad practice’ nay-sayers are missing is that many companies have mobile versions of their websites which need to detect mobile browsers.

    • No, the “naysayers” are likely not in that unfortunate group (those that have painted themselves into a corner with bloated GP libraries and other poor practices).

      And they do not “need” to detect any such thing. Think.

  17. Guys, this is not a good way to serve an alternate site for mobile. It doesn’t matter what the name or user agent of the device is. What matters is if the device has the capabilities to perform the things you need it to do.

    If a new mobile phone gets released tomorrow that does everything an Android can do, it should see your mobile website too no matter what user agent it has.

    For a better solution see modernizr. http://www.modernizr.com/

  18. Browser sniffing is a stupid, error-prone and reviled practice, “backed” by a decade of failures. Doing it on the server side is completely clueless as you could very well be talking to a proxy.

    http://www.jibbering.com/faq/notes/detect-browser/

    And what does the string “Android” imply? Absolutely nothing, not even that the screen is small (use media queries to detect that).

    Do not use this code (or code that resembles it) under any circumstances.

    • Bryce

      Every situation is different, and to say a method is “Stupid” because it is not optimal for your situation is, well, Stupid!

      Grow up and think outside of your own circumstances, for everyone’s sake ;)

    • David, I’m not agree with your comment at all… first of all MediaQueries are great for size(width|height) detection, orientation in mobile browsers that support, aspect-ratio (not very used) and some more stuff like the media (screen|print|etc).

      Also, mobile browsers has there own limits that media-query cannot detect, for example iOS has a limited way to read fixed elements, but can be used with caution, android browser has a lot of other limitations, and are a lot of display formats as are a lot of display androids, so you can’t judge if is an android from a MediaQueries .

      Something more, MediaQueries could look nice when you want to make the same webpage and mobilepage, but even if you see less content and aside stuff stay hidden, are loaded… so the page has a lot of extra content to load, that is not good either.

      Maybe you don’t have the enough experience working with mobile development and repeat something you read in other post, if that is true, be more carefuly to what you say, be sure of your knowledge and never judge the others knowledge… you can say “I don’t share it”, no “It’s stupid” , for your own good =)

  19. The navigator.userAgent value can not determine whether or not it is an android tablet, or an android smartphone. Detecting window.innerHeight or screen.height won’t help either as HD phones have similar resolutions to non-HD tablets!

    Is there a better solution?!?

    I need to forward the user to the mobile site when they are on a smartphone, while tablet users would see the normal “desktop” version of the site.

    • If you use the meta tag viewport, will help in all of the devices that are able to handle with the information, to specify the width that your page should be rendered and other stuff.

      That will be applied for any display size.

      Research a little more about this and the device-pixel-ratio css property.

      I hope this could be helpful

  20. A good read about using media queries to detect device/browser:

    http://www.cloudfour.com/css-media-query-for-mobile-is-fools-gold/

    They aren’t always as reliable as preached.

  21. I will also point out that before completing this post, I checked jQuery Mobile, Sencha Touch, Phone Gap, etc. They all appear to use UA sniffs. I’ve also not yet been provided a better solution by anyone. I’m more than receptive to receiving one.

  22. To counter the older post nay-saying media queries I’ll point to a newer one promoting them: http://www.html5rocks.com/mobile/mobifying.html

    Also, the compat tables referenced by the cloudfour article are ~2yrs old. Media queries should work great for Android devices now.

    Android’s own dev site has a post on them+viewport-metas+JS: http://developer.android.com/guide/webapps/targeting.html

    • FWIW, the article referenced–the one I wrote–was written on August 3, 2010, not two years ago. The compat tables referenced were tests conducted on real devices during the period of August 1-3 of last year.

      Files downloading for display:none img tags is still an issue on iOS. Hence the responsive images js code that the Filament Group has developed for the Boston Globe project they are doing with Ethan Marcotte:
      https://github.com/filamentgroup/Responsive-Images

      FWIW, most major sites delivering mobile optimized content are still using some aspect of server-side detection–usually in conjunction with client-side feature detection. I know from conversations with Google that they do this and Facebook has been very open about their use of device detection:
      http://www.facebook.com/notes/facebook-engineering/crowdsourcing-mobile-device-capabilities/441195668919
      http://www.facebook.com/note.php?note_id=10150122073713920

      I echo the comments of those who note the specific requirements of a project or product–particularly what devices you need to support–may necessitate different tools. Like most things, it depends.

    • Jason, I wrote that the *compat tables referenced are ~2yrs old*.

      You should also note that Google/Facebook have gobs of devs to monitor and tweak their UA sniffs when new browsers/devices come out.

      As I’ve said before, UA sniffing should be a last resort not a knee-jerk first.

    • John-David,

      Just stumbled back on this post and your response. I had forgotten about the link to PPK’s tables. I thought you were referring to my tests of mediaqueries, not the link. My mistake.

      -Jason

  23. David, You rock! Thanks for the free code.

  24. Thanks for the snippet. Yeah the mobile web is a tricky beast. Not easy to find the most “correct” path. Context is everything.

    “Were I to invoke logic, logic clearly dictates that the needs of the many outweigh the needs of the few.”

  25. neil

    Using the default browser on my HTC Desire no user_agent identification code works.

  26. I think some are missing the point. The detection isn’t there just to redirect to a custom Android page/site. It can be used to enable or disable page elements. For example TinyMCE editor works great in iPhone and iPad, but dies a death on my HTC Sensation. Therefore, I need to ensure that I can disable TinyMCE on Android and serve a different text input.

  27. Ben Walters

    This is only ‘bad practice’ with it’s implementation. If you are using this to re-direct to mobile sites, then this being ‘bad-practice’ is the least of your worries (Media Queries, .htaccess… come on!?).

    BUT, if you are using this to, for example, serve up a link to the android market for android users, and a link to the AppStore for IOS devices, using the us sniff to hide and show elements, then i fail to see any kind of poor implementation practices. This is a seemingly 2D snippet, with a huge range of applications.

    Get inventive!

  28. Best user agent detector in the world here http://tinytop.mobi Last update 02.02.2012 Please make a topic about this.

  29. Robocat

    The best cross-browser way I have found to detect touch devices is to use:

    var isTouchDevice = (‘ontouchstart’ in document.documentElement);

  30. Robocat

    However the above doesn’t allow the user to use the “Request desktop site” feature of 4.0 and Chrome Mobile.

  31. gaurav

    Hi i’m the new one for this blog i have a problem with my app
    i”m using navigator.language for detect the language of the device and this is working in iPhone but non other Android phones.
    so what i need to use for android.

    Gaurav

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

  33. Thanks a lot for the snippet, David!!!!

    I didnt get an embedded Youtube Clip to play on Android devices ffs. Well, at least on the two different HTC models (Desire) my GF and me have in use. Desktop Win & Mac Pcs worked fine as did iPhone, iPad and even a Samsung Tablet with Android installed. Found out, that i had to use the old object/embed method instead of the late iframe method provided by Youtube for Android devices. I gratefully took your code, added a bit of if/else and an document.write to it and voilà!

    Thanks a lot for this fine site and the great help you provide!!!

    Greetings from Germany,

    thosch

  34. Thanks a lot for the snippet, David!!!!

    I didnt get an embedded Youtube Clip to play on Android devices ffs. Well, at least on the two different HTC models (Desire) my GF and me have in use. Desktop Win & Mac Pcs worked fine as did iPhone, iPad and even a Samsung Tablet with Android installed. Found out, that i had to use the old object/embed method for Android devices instead of the late iframe method provided by Youtube. I gratefully took your code, added a bit of if/else and an document.write to it and voilà!

    var ua = navigator.userAgent.toLowerCase();
    var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
    if(isAndroid) {
    	document.write("");
    } else {
    	document.write("");
    }
    

    Thanks a lot for this fine site and the great help you provide!!!

    Greetings from Germany,

    thosch

  35. Love it when I search for something and find the answer at one of Name.com’s most awesome customers website.

  36. Matt

    Thank you for this!

    For people advocating that you must or must not do XYZ, please stop.
    There really isn’t any *rules* to web development, just *guidelines*

    If your in a bind, the client is shouting down the phone, really, the idea of being overly evangelistic in your craft somewhat goes out of the window.

    In an ideal world, or in a wonderful world where you have no clients, no deadlines and exist just to do research (you lucky person!) – sure, knock yourself out, don’t ever use UA detection.

    I’m using this Javascript agent detection to get around the issue with Android and fixed position elements. I have a horizontal flyout menu in a fixed position. Works *perfectly* on *every* other browser, device – you name it – except android.
    Fixed position elements is a known issue with android browsers.

    So, a simple UA detection and I can modify the CSS for the sidebar just for android.

    Works for me.

  37. android

    I know UA detection is bad practice, however: what’s the best practice if I just want to show a link to my Google Play app iff the user is on an android device?

  38. Man you just saved my life! HAHAHAHAHAH thanks!

  39. Conor

    Thanks David! Nice and clean.

  40. What do you do if a specific version of safari on a specific version of IOS iphone 4 is not supporting innerwidth and innerheight and you workaround by scrolling to the bottom of the page when you need it, then scrolling back (convoluted example, but yes, this is how it works on safari on IOS iphone 4). What do you do for this situation? This is an extremely specific bug on ios despite innerwidth and innerheight being “supported”.

  41. Hello,

    I have a question about this that I not saw anywhere. How can we do, if for example we want to detect when a user visit our webpage trought Android device and we want to show some message or popup to recommend or suggest to download our application published on Google Play?

    Thanks at all,

  42. This method of Android detection will fail in some cases.

    I have a cheap Android tablet (an All winner A13), and it’s user-agent string DOESN’T CONTAIN “Android” (in fact it claims to be an early iPad).

    However every Android device I’ve seen (which is admittedly, not very many) has the navigator.platform string “Linux armv71”.

    So my recommendation for JavaScript would be to look for “Linux arm” in navigator.platform.

    Not sure what to suggest for PHP though …

  43. Just to expand on the code slightly, as there are some css issues with androids stock browser in older devices, you may want to try out this to determine if it’s androids stock browser or chrome.

    I’m sure there are other edge cases but this may help someone out.

  44. $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
    
    	if(stripos($ua,'chrome') !== false) {
    	echo "ANDROID - GOOGLE CHROME";
    	} else {
    	echo "OLD STOCK ANDROID BROSWER";
    	}
    
    }
  45. But how can we check the difference between Android in-app webview or just the Android browser.
    I want to hide some Adsense code with php when the website is runned from the in-app webview. But when the app is runned just from the mobile browser it can show Adsense. It’s against the terms and conditions running Adsense in in-app

  46. Alfonso

    the only issue with user agent for android detection with user agent is that once the customer selects desktop view on the browser, yoo not longer can detect it as android

  47. Will this detect users that use apps to access your content?

  48. Patanjali

    Modern Android phones tend to make text in browsers about 10% larger than on other OSs, making text placed by position larger and possibly wrapping around compared to iOS and desktops.

    Unfortunately, the user agent strings these days are stuffed with popular OS and browser identifiers so that sites are not disadvanteged by the OS and browsers used.

    For example, the Lumia 950 XL Edge browser cites Windows 10 and Android, even though it doesn’t do the upsizing that standard Android does.

    Basically, user agent sniffing is unreliable just because it is defined by the arbitrary whims of browser designers

  49. I has problem defect Android 10 or 6.0.1 and how fix it?

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