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

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|sagem|sharp|sie-|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:
24/03/2011 – Updated for Android
25/04/2011 – Updated for Windows Phone 7
23/05/2011 – Updated for iPod Touch
16/01/2012 – Rewritten, shortened. Deleted unnecesary checks. Added Windows CE support.

    • Ryan Tuttle
    • March 24th, 2011 3:59pm

    Thanks for the script! I tried it and it worked on my iPhone but it didn’t detect my Xoom as being a mobile device. I know the User Agent for the Xoom has the word “Android” in it (as well as “Xoom”) is this just not picking it up for does it not pick up any Android devices? It is also completely possible, and more likely, that I messed something up.

  1. Updated for Android. Give it a try and let me know if it doesn’t work.

      • milan
      • November 15th, 2011 10:21am

      Doesn’t work for me my android phone doesn’t redirect and i dont know wat to do

      • milan
      • November 15th, 2011 10:25am

      My friend jasper and i are hopeless and dont know what to do

    • Jim
    • March 30th, 2011 10:20am

    Danny,
    Thanks for the posting and update. I just added the “android” and “ipad” to the pregmatch in line 07 and it seems to deliver the same functionality as the added lines 35-45.

    • bvd
    • April 12th, 2011 2:09pm

    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
    • April 12th, 2011 3:18pm

    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
    • April 12th, 2011 3:31pm

    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
    • April 25th, 2011 10:06am

    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.

    • eavillar
    • May 2nd, 2011 6:09pm

    Hey! Thanks for the script Danny!

    • Josh
    • May 18th, 2011 11:24am

    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
    • May 18th, 2011 9:57pm

    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
    • May 22nd, 2011 9:41am

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

      • waiwaizu
      • May 22nd, 2011 9:46am

      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
    • May 23rd, 2011 9:36am

    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!

  2. 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
    • June 2nd, 2011 2:16am

    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
    • June 30th, 2011 8:21pm

    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.

  3. 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
      • July 30th, 2011 10:21am

      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.

  4. 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
    • August 2nd, 2011 11:51pm

    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)

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

  6. Hey,

    im using your detection way, but ive problem with Opera under Macintosh. It doesn’t work there.

    When i’m adding following code, it works. But i don’t know if it is the right way.

    if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), ‘macintosh’) !== false)
    $mobile_browser=0;

    Maybe other mobile apple devices use also macintosh.

  7. Otimo script, obrigado.

    Parabéns.

    Ats. Jorge

    • Dmitry
    • September 1st, 2011 2:15pm

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

    • Julio
    • September 1st, 2011 5:50pm

    Hi im using opera mini @ windows. And like to pass validation, so at first add:

    if(preg_match(‘/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom|mobi)/i’, $_SERVER['HTTP_USER_AGENT']))

    mobi string to first check. And bypass windows validation. If the Reg Exp return true.

    And think that strtolower is not useful at this line, because youre using /i modificator (incase sensitive)

    • Jérémy
    • September 7th, 2011 2:46am

    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 ?

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

    • Jérémy
    • September 10th, 2011 2:29am

    Hi,

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

  9. Hi,

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

    • Richard
    • September 30th, 2011 8:36am

    Here’s a slightly more compact version. Thanks for the function :-)

    $MOBILE_AGENTS_RE = “up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom”;
    $MOBILE_AGENTS4 = array( ‘w3c ‘,’acs-’,'alav’,'alca’,'amoi’,'audi’,'avan’,'benq’,'bird’,'blac’,'blaz’,'brew’,'cell’,'cldc’,'cmd-’,'dang’,'doco’,'eric’,'hipt’,'inno’,
    ‘ipaq’,'java’,'jigs’,'kddi’,'keji’,'leno’,'lg-c’,'lg-d’,'lg-g’,'lge-’,'maui’,'maxo’,'midp’,'mits’,'mmef’,'mobi’,'mot-’,'moto’,'mwbp’,'nec-’,
    ‘newt’,'noki’,'oper’,'palm’,'pana’,'pant’,'phil’,'play’,'port’,'prox’,'qwap’,'sage’,'sams’,'sany’,'sch-’,'sec-’,'send’,'seri’,'sgh-’,'shar’,
    ‘sie-’,'siem’,'smal’,'smar’,'sony’,'sph-’,'symb’,'t-mo’,'teli’,'tim-’,'tosh’,'tsm-’,'upg1′,’upsi’,'vk-v’,'voda’,'wap-’,'wapa’,'wapi’,'wapp’,
    ‘wapr’,'webc’,'winw’,'winw’,'xda’,'xda-’);

    $mobile_browser = false;
    $http_useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $http_useragent4 = substr($http_useragent,0,4);
    $http_all = strtolower($_SERVER['ALL_HTTP']);
    $http_accept = strtolower($_SERVER['HTTP_ACCEPT']);

    if ( (preg_match(“/($MOBILE_AGENTS_RE)/i”, $http_useragent))
    or (strpos($http_all, ‘operamini’) !== false)
    or (in_array($http_useragent4, $MOBILE_AGENTS4))
    or (strpos($http_accept,’application/vnd.wap.xhtml+xml’) !== false)
    or (isset($_SERVER['HTTP_X_WAP_PROFILE'])) or (isset($_SERVER['HTTP_PROFILE'])) ){
    $mobile_browser = true;
    }
    if (strpos($http_useragent, ‘windows’) !== false){ // Pre-final check to reset everything if the user is on Windows
    $mobile_browser = false;
    }
    if(strpos($http_useragent, ‘windows phone’) !== false){ // But WP7 is also Windows, with a slightly different characteristic
    $mobile_browser = true;
    }

    • Kris
    • October 8th, 2011 12:13am

    Just thought I would point out that you have “winw” specified twice in the $mobile_agents array.

    Later!

  10. 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
    • October 10th, 2011 10:45pm

    some greetings from holland

    May i thank you for the code its working perfect !

    cheers john

    • George
    • October 13th, 2011 4:30pm

    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?

  11. Thanks a lot for sharing! Really helpful!

    • wysiwyg
    • November 3rd, 2011 4:46am

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

    • Jake
    • November 14th, 2011 4:38pm

    I used it so iqdit!

    • jesbomar
    • November 21st, 2011 4:22pm

    Hi,

    I get an error, saying <>. If i search here:

    http://php.net/manual/en/reserved.variables.server.php

    The index “ALL_HTTP” does not exist. Anyone nows the solutions? Which mobile devices am I missing by not incorporating that line of code?

    Thanks a lot!

  12. 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
    • November 30th, 2011 12:34pm

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

    • Ben
    • January 3rd, 2012 9:43am

    Thanks Danny, this works well.

    • Vlad
    • January 5th, 2012 9:38am

    Thanks Danny, this works well.

    • Carlos
    • January 8th, 2012 2:02am

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

    Hugs from Beijing

  13. why is var $mobile_browser in line 5 initialised as string. but cool script though.

    • Andy
    • January 11th, 2012 12:48pm

    doesn’t work for my phone:
    user agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows CE; IEMobile 8.12; MSIEMobile 6.0) T-Mobile_Maple

    I updated the script with:
    // But WP7 is also Windows, with a slightly different characteristic
    if(strpos($agent, ‘windows phone’) !== false || strpos($agent, ‘windows ce’) !== false)
    $mobile_browser++;

    now it works.
    Thanks anyway!

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

    • Guillaume
    • January 18th, 2012 11:30pm

    Thanks a lot! Works like a charm. Cheers!

    • Andrew Miguel
    • January 20th, 2012 4:57am

    Thanks Danny for the little but useful script.

    • Alwin
    • January 30th, 2012 4:58am

    Thanks, great script.

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

  15. BTW, excellent, simple script. Thanks!

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

    • Razvan
    • February 18th, 2012 3:25pm

    Thanks, it works great !

  1. May 17th, 2011
  2. August 26th, 2011
    Trackback from : Anonymous
  3. January 4th, 2012

follow me on Twitter