Detect mobile browser/user agent with PHP (iPad, iPhone, Android, BlackBerry, WP7 and others)

Posted by on Feb 2, 2011 in Backend | 80 comments

With all this load of smartphones and tablets, it is mandatory for us as developers to optimize our content as much as possible so everybody can see it, no matter what device they are using. This is why I wrote a small but powerful function to properly detect a wide range of mobile devices and redirect to an special content accordingly.

Lets take a look:

function detect_mobile()
{
	if(preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $_SERVER['HTTP_USER_AGENT']))
		return true;

	else
		return false;
}

This function can detect most (if not all) of all the standard “dumb” phones, smartphones, including the iPhone, iPad, Android and Windows Phone 7. Lets say you want to redirect your users to your blog if they are accessing your home page from a mobile device:

$mobile = detect_mobile();

if($mobile === true)
	header('Location: blog');

Nice and easy!

Changelog:

06/06/2012 – Added PlayBook and Kindle Fire support.
16/01/2012 – Rewritten, shortened. Deleted unnecesary checks. Added Windows CE support.
23/05/2011 – Updated for iPod Touch
25/04/2011 – Updated for Windows Phone 7

24/03/2011 – Updated for Android

  • bvd

    sorry for being such a noob, but is the above supposed to be two separate files? not sure how to implement this…

    Thanks!
    -bvd

    • Not necessarily. You can have the function and the call in the same file. The “if($mobile === true)” condition will help you decide what to do if the detected user agent comes from a mobile device.

      That particular example redirects the user to a /blog folder if the user agent matches one of the mobile browsers supported by the function.

  • bvd

    ok, so I can just put the call at the en of the file?

    when I browse from the computer it works, but when I browser fro my android phone I get:

    Warning: Cannot modify header information – headers already sent by (output started at /home/”account”/public_html/test.php:65) in /home/”account”/public_html/test.php on line 69

    Here’s my file:

    0)
    return true;
    else
    return false;
    }
    ?>

    Untitled Document

    this is the normal site

    • The function call must be at the beginning of the file if you are doing a redirect with a header(). Remember that headers cannot be sent if you already echoed something else.

  • bvd

    Oh yeah, my bad… Works great, thanks!

    Got any tips on making paged optimized for android phones?

    bvd

    • – Don’t use jQuery (you can use jQuery mobile though).
      – Keep it as light a possible.
      – Don’t use large images.
      – Make it XHTML standard.
      – Use HTML5 if you can.
      – Allow a liquid width in your design, so people wont have to scroll with their fingers horizontally.

  • Ste

    This doesn’t look like it will handle Windows Phone 7 very well. A typical user agent for some windows phone 7 phones contains “Windows Phone OS 7.0”. I’m thinking it would work just to change the line checking for “windows” and add another check looking for “phone”. Something like this:

    if((strpos(strtolower($_SERVER[‘HTTP_USER_AGENT’]), ‘windows’) !== false) && (strpos(strtolower($_SERVER[‘HTTP_USER_AGENT’]), ‘phone’) !== true))

    • Updated for WP7. Give it a try and let me know if anything goes wrong.

    • jason

      “phone” is in the list so windows phone will get discovered as a mobile device. no need to check “windows” and “phone” together.

  • eavillar

    Hey! Thanks for the script Danny!

  • Pingback: Conditional for Mobile – Ideas & Inspiration()

  • Josh

    Trying to get this working now, would it be possible to get a link to a website that’s using it? Would love to see it in action.

  • Opencode

    Thanks Danny.

    ipad, samsung tab, … have moble browsers but it screen is large.
    so if this code can detect pads also, it may be more usefull.

    $mobile_browser : true/false
    $mobile_pad : true/false

    • Actually, the code is most likely to be used because of Flash. You see, Flash content is not rendered by the iPad. Even if it has a large screen, it doesn’t mean it will render flash, hence this function.

      I don’t think there is really a need to use the function if the page has no Flash content since most of the modern devices, even smartphones, can render XHTML and JS just fine.

  • waiwaizu

    how to support with ipod touch!?
    dont work with ipod!! pls

    • waiwaizu

      and i also want to ask how to change back to desktop version,
      such as u load in mobile version, then u click the link, that will be change back to desktop version and remember it! thx!!

    • Currently it doesn’t support the iPod touch. However, since the iPod touch has the same browser as the iPad, it should be detected as well. If it doesn’t, I would need the USER_AGENT to modify the function.

      Regarding changing back to the desktop version, you will need to use sessions. If some session var is not set, you display the mobile version, if it is, display the desktop version.

    • I’ve updated the function for the iPod touch. Give it a try and let me know if it works.

  • Hayezb

    First of all, thank you for this script! It’s almost exactly what I’ve been looking for… I want to have my users re-directed to a “mobile” version when viewing from a phone (Android, iPhone, etc…) but I do not want to when viewing from a tablet.

    What steps do I need to take to do this?

    Thanks!

  • Laurent

    Good Morning,
    I found your work thrue google and I would like to use it to find the mobile
    I m not very good under php but I like flash.
    Reason why I need your help to switch the content if its a mobile, Iphone or Ipad

    Can you show me a way to find it ?
    I understand the call but how to load a different page if its ipad, iphone, android or let the current page if not ?

    Thank you very much

    Laurent

    • To redirect the user to a different page when visiting from a mobile device, just take a look at the “header()” like of the code, its close to the bottom of the post, there you can set the relative path of the alternate version to display.

  • waiwaizu

    Danny Herran :
    I’ve updated the function for the iPod touch. Give it a try and let me know if it works.

    Thats ok, thx!

  • Mo

    Hello, firstly, I am a noob to PHP. I thought I could get this to work, but no luck. Here is my issue: I DO NOT KNOW WHAT I AM DOING.

    I am trying to add this into my index.html page.

    Do I take the code above and save as mobile.php?
    Do I then upload that file to the root of the server?
    Do I add this to my html page

    $mobile = detect_mobile();

    if($mobile === true)
    header(‘Location: blog’);

    and re-save as a php file?

    If I do all of this, how does the server know to check the mobile.php file to re-direct? Help is appreciated.

    • Rename your index.html file to index.php. Then add that code to the first line of the index.php file. Execute in a PHP compatible server and enjoy.

  • Emiliano

    One thing that would be cool is to give the user the option to override the user agent, and to see the desktop version of a website. Because if they want, with this they cant.

    Any thoughts?

    • Steven

      This is a php function to determine browser/user agent. In the case of this script, the function provided gives php developers a way to determine if the user is using a mobile device … what you then do with it then is limited only by your imagination, hence why no such option is available by the detect_mobile() function itself.

      If you need to override the mobile output of detect_mobile(), then you need to look at integrating detect_mobile() with a script that uses sessions, cookies or simple variables, to orverride the output you get from detect_mobile().

      For example, if the page in which you call detect_mobile() listened for a GET variable (perhaps from a link that was called ‘Desktop version’), you could tell your page to ignore whatever detect_mobile() outputs in favour of desktop orientated content. Simple as that.

  • Hi danny i had a question about directing to mobile devices.
    I have a website pureandnaturaltreats.com and want to direct that to a mobile device called pureandnaturaltreatsmobile.com
    how do I get it that when someone goes to pureandnaturaltreats.com on a mobile device to redirect them to the pureandnaturaltreatsmobile.com can it be done through the index.html?

    Thank you for your help
    Philip

    • With header() you wont be able to achieve that because we’re are talking about a different domain here. However, I believe you could echo a meta-refresh tag or a javascript redirect in order to send the user somewhere else. Using a meta refresh would be even cooler, because you could do something like: “Please wait a moment, you’re being redirected to a mobile version of this site…”. Just a thought.

  • eliecer

    I used both codes, one after the other one inside a php file as show below:

    0)
    return true;
    else
    return false;
    }

    $mobile = detect_mobile();

    if($mobile === true)
    header(‘Location: http://www.google.com‘);
    else
    header(‘Location: http://www.cnn.com‘);

    ?>

    I just modified the last conditional inside the code. If the user is using a mobile device, they will be redirected to google (replace with your own website address), if they are not using a mobile device, they will be redirected to cnn website (replace with your own website address).

    In the mobile site, you can create a button to redirect people to the regular website (if they wanna visit the no mobile version of the site)

  • The other long code goes also at the top of your index.php page. Before the conditional.

  • Otimo script, obrigado.

    Parabéns.

    Ats. Jorge

  • Dmitry

    OMG, I LOVE YOU!!! and it was very easy to rewrite in Perl!!!

  • Jérémy

    Hi,

    thanks for the code.

    When I’m using Opera on Linux (seems to be everytime) the code “thinks” I’m using a mobile phone :\. Do you know why ?

  • What does the http user agent say for Opera on Linux ?

  • Jérémy

    Hi,

    the http_user_agent says Opera/9.80 (X11; Linux x86_64; U; fr) Presto/2.9.168 Version/11.51

  • Hi,

    the code works, it was a mistake on my own code…^_^…

  • Fixed some issues with the previous code. The whole function will be rewritten soon. I will post the update as soon as its done.

  • John van Berkel

    some greetings from holland

    May i thank you for the code its working perfect !

    cheers john

  • George

    If its from a Smartphone I want redirect to domain (“a”) and if it’s from a tablets I want redirect to domain (“b”) how can I do this?

  • Thanks a lot for sharing! Really helpful!

  • wysiwyg

    Firstly awesome script big ups. It works perfect but would like to know where to have a look at the updated change log

  • I used it so iqdit!

  • Thanks Danny! Easy to implement and works like a charm. I used it to dynamically rewrite mouseover hover effects so that they did not kick in for touch devices.

  • Kit

    Thanks Danny, script works great! Thank you for sharing…

  • Ben

    Thanks Danny, this works well.

  • Pingback: Interested in Your WordPress Theme Best Practices – The Volo Report()

  • Vlad

    Thanks Danny, this works well.

  • Carlos

    Cool! easy to understand & update to our php site. Thanks for join with us your function, it’s really usefull 😀

    Hugs from Beijing

  • I updated the function and added support for Windows CE.

  • Guillaume

    Thanks a lot! Works like a charm. Cheers!

  • Andrew Miguel

    Thanks Danny for the little but useful script.

  • Alwin

    Thanks, great script.

  • You should really add support for the BlackBerry PlayBook (playbook) and the Kindle Fire (silk)

  • BTW, excellent, simple script. Thanks!

  • Thank you for this great and simple useful script that saved my hours !

  • Razvan

    Thanks, it works great !

  • Please how can this same code to differenciate high end devices from the normal wap phones. for instance i want to redirect people using highend devices to siteA and the other people using just wap phones like nokia to pageB and people using blackberry to pageC.

    Please any help would be appreciated. thanks

  • Pingback: html request to server from different devices | PHP Developer Resource()

  • Rizwan

    nice and simple

  • Jason

    It’s really very practical code, I love it, thank you so much and I will keep noticing your post.
    Thanks for sharing again!

  • Jason

    Hi, got a suggestion, sometimes a mobile browser doesn’t send an UA symbol, and among all empty UA headers most of them is mobile browsers.

    Is there anyway support empty UA? following is pieces of log on my server:
    211.142.189.200 – – [06/Aug/2012:13:59:48 +0800] “GET /haiying-news/n120.html HTTP/1.0” 200 11348 “-” “http://www.hiwins.com/” “-”

    You can see that there is no UA, in fact I’m using Blackberry 8800.

    Thank you and waiting for your response.

    • I might be wrong here but I would go ahead and say that pretty much every desktop browser adds the UA to the headers. So, considering this, if there is no UA in the headers then the user is probably and most likely browsing from a phone. Based on this you can update the function for that particular need.

    • Jason

      Thank you for your notice and notice, yes I agree with you much.
      Yet as a pity I do not know well about PHP, I’ve tried many ways to express but all failed, I suppose a “-” should be added in, I tried but failed:

      ….
      if(preg_match(‘/(….|zte|”-“)/i’,
      ….

      Do you have any ideas on this?
      BTW: You can also consider this as an update in the code.

  • jason :

    “phone” is in the list so windows phone will get discovered as a mobile device. no need to check “windows” and “phone” together.

    Actually, Windows CE doesn’t have the “phone” string in its UA. So, both words should remain if we want to detect Windows CE, Windows Mobile and Windows Phone 7/8.

  • hacklover

    Thanks, excellent function

  • Adit

    Nice… thanks bro!

  • Adam

    Thanks for the script.

  • BGN

    Hi, I’m viewing this site using blackberry 9900: and I would like to to believe that the version of the site that I’m viewing is a desktop version or tablet version. I think on your function you should devide your function into 3 deciders or four. One for desktop, two for tablets, 3 and 4 for mobiles, mobiles having to sub-heads, full touch screens and normal mobiles. And again. I think it is important to allocate you if statements very well, and if a deviced was first detected as a windows desktop while it is a mobile inside that if statement use a second if stament to see if it’s not a mobile device and if it is redirect it to the 3 and 4th if statement using OOP class. That’s the nice thing about OOP PHP

    • What you see is a desktop version of the site. I’ve been too lazy to develop a mobile theme for my own site :). Your idea sounds great. It would require some testing because some Android tablets have the same user agent as mobile phones, but thank you for your input. I would certainly take it in consideration for the next update of this function.

  • Andrew Reed

    I’d use a switch instead of ifs & elseifs

  • Vancers

    Hey Danny, just wanted to chime in with a big THANK YOU! Looks perfect, and I’ll let you know how it works out.

  • chaozz

    I was looking for a simple solution to detect mobile devices for my game, and this works perfectly. Thank you!

  • Rick

    Hello, I’m trying to use your codes as a guide to have certain ads banner displayed on desktop only. This is what I have, which I pasted in header.php where I want to display the ad:

    function detect_mobile()
    {
    if(preg_match(‘/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i’, $_SERVER[‘HTTP_USER_AGENT’]))
    return ”;

    else
    return ”;
    }

    What am i doing wrong?

  • Rick

    Hello, I’m trying to use your codes as a guide to have certain ads banner displayed on desktop only. This is what I have, which I pasted in header.php where I want to display the ad:

    function detect_mobile()
    {
    if(preg_match(‘/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i’, $_SERVER[‘HTTP_USER_AGENT’]))
    return ”;

    else
    return ”;
    }

    What am i doing wrong?

  • Rick

    looks like its stripping the codes i wrote on the return lines.

    but it’s a code

  • الدفاع

    Excellent work.

    Anyone know what to put in for blackberry? The other mobile users are having no issue but can’t get the right agent for blackberry.

  • Diana Morgan

    Wow, incredible blog layout! The overall look of your site is fantastic, let alone the content!

  • Arun Chandran

    Great Code…Thank you very much..:) !!!