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.


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.
Updated for Android. Give it a try and let me know if it doesn’t work.
Doesn’t work for me my android phone doesn’t redirect and i dont know wat to do
My friend jasper and i are hopeless and dont know what to do
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.
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.
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.
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.
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.
Hey! Thanks for the script Danny!
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.
Here you go:
http://www.compumall.com.ve
http://www.screenmediagroup.com
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.
how to support with ipod touch!?
dont work with ipod!! pls
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.
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!
In line 7, remove iPad and Xoom from the regular expression. However, for Android, there is no implemented standard yet. For instance, the Samsung Galaxy Tab on Android 2.2 uses the same user agent as any other Android device, so it would be impossible to differentiate.
Android 3.0 tablets can be easily differentiated by the OS version.
Check this out for more information: http://stackoverflow.com/questions/5341637/how-do-detect-android-tablets-in-general-useragent
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.
Thats ok, thx!
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.
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?
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.
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.
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.
Otimo script, obrigado.
Parabéns.
Ats. Jorge
OMG, I LOVE YOU!!! and it was very easy to rewrite in Perl!!!
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)
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 ?
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…^_^…
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;
}
Just thought I would point out that you have “winw” specified twice in the $mobile_agents array.
Later!
Fixed some issues with the previous code. The whole function will be rewritten soon. I will post the update as soon as its done.
some greetings from holland
May i thank you for the code its working perfect !
cheers john
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!
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!
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!
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.
Thanks Danny, script works great! Thank you for sharing…
Thanks Danny, this works well.
Thanks Danny, this works well.
Cool! easy to understand & update to our php site. Thanks for join with us your function, it’s really usefull
Hugs from Beijing
why is var $mobile_browser in line 5 initialised as string. but cool script though.
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.
Thanks a lot! Works like a charm. Cheers!
Thanks Danny for the little but useful script.
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 !
Thanks, it works great !