PHP: Extremely simple way to check if it is a Mobile Browser

This is just a Snippet to check wether the webbrowser the viewer has is a mobile browser (like the standard Android/iOS browser)

As the standard Android and iOS (and probably more mobile webbrowsers) has the word “mobile” in it’s HTTP_USER_AGENT, we just have to check wether it is there or not.

Android Default: TRUE
iOS Default: TRUE
Opera Mobile Android: TRUE //Changing “mobile” to “mobi” will fix for opera, but not sure if any desktop versions has “mobi” in it.
FireFox Mobile Android: TRUE //Changing “mobile” to “Android” should make it working for Android browsers, so adding an || (OR) will show iOS and most common Android Mobile Browsers.

if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
   echo "You are running a mobile webbrowser!";


Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2

To make things a little easier here’s the QR code of that url.

Thanks, I didn’t think about that :wink:
I’d karma you, but the karma button is beeing a ■■■■■ right now…

From my BB 9300:

Mozilla/5.0 (BlackBerry; U; BlackBerry 9300; en-GB) AppleWebKit/534.8+
(KHTML, like Gecko) Version/ Mobile Safari/534.8+
Mobile Browser

What’s up with it?

Okay, your BB is fine :wink:

Well, it tells me I have to spread karma a bit around before giving him more, but it says so on every user I try to karma :stuck_out_tongue:

Although I admire the willingness to try and help others, according to the WURFL list, your Mobile Device Detection snippet, only catches about %14 of the listed mobile devices on the WURFL list.

Plus, strstr() is not the best way of detecting a string within a string. As it Notes on the page.

The following Class matches %97.9 of the WURFL listed UserAgents.


*  Mobile Detection RegEx (2/3) Supplied By
*  Regex updated: 22 August 2011
*  Before Using You Must Include The Class Script In Your Page:
*  require_once('class.DetectMobileDevice.php');
  Static Approach
    DetectMobileDevice::Redirect(string $redirectPath [, bool $includeRequestURI=false]); 
        Returns: Nothing, redirects request on detection of mobile device.
        Returns: (bool) True/False. True ~ if mobile device detected.
  Object Approach
  - Detect if mobile
    $obj = new DetectMobileDevice(string $redirectPath [, bool $includeRequestURI=false]);
      // User is on Mobile Device - Do Something
      // User is NOT on Mobile Device - Do Something Else or Nothing
  - Detect and Redirect
    $obj = new DetectMobileDevice(string $redirectPath [, bool $includeRequestURI=false]);
    $obj->fullRedirect(true); // Include Request URI
  Example #1: Redirect Mobile Users to 'mobile' directory, without the Requested URI
    $obj = new DetectMobileDevice('mobile');
    The user requested and was redirected to
  Example #2: Redirect User To Subdomain, with requested URI
    DetectMobileDevice::Redirect('', true);
    $obj = new DetectMobileDevice('', true);

    The user requested and was redirected to

*  ** NOTE **
*  After the first call to DetectMobileDevice::Mobile(), wether or not the UA is a mobile device's,
*  is stored in a static variable, so multiple calls to DetectMobileDevice::Mobile() will not cause
*  multiple checks. The original check will be returned. (System Resources will not be taxed with
*  multiple RegEx checks) 

class DetectMobileDevice {
  protected  $_useragent;
  protected  $_redirect;
  protected  $_full_redirect;
  public static $dmd;
  /**  Magic Methods  **/
  public function __construct($redirect, $fullRedirect = false){
    $this->_redirect = $redirect;
    $this->_useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $this->_full_redirect = $fullRedirect;
  /**  Protected Methods  **/
  protected function _is_mobile($useragent){
    if(strpos($useragent, 'mobile') !== false || strpos($useragent, 'android') !== false){
      return true;
    }else if(preg_match('/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/',$useragent)){
      return true;
    }else if(preg_match('/(bolt\/[0-9]{1}\.[0-9]{3})|nexian(\s|\-)?nx|(e|k)touch|micromax|obigo|kddi\-|;foma;|netfront/',$useragent)){
      return true;
    }else if(preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/',substr($useragent,0,4))){
      return true;
    return false;
  protected function _additional(){
      $uri = trim($_SERVER['REQUEST_URI'], '/');
      return (isset($uri{0}))? ((substr($this->_redirect, -1, 1) === '/')? '' : '/') . $uri : '';
      return NULL;
  /**  Public Methods  **/
  public function detectAndRedirect(){
    if($this->_is_mobile($this->_useragent) && strlen(trim($this->_redirect,'/')) > 0){
        echo '<meta http-equiv="refresh" content="0; url=' . $this->_redirect . $this->_additional() . '">';
        header('Location: ' . $this->_redirect . $this->_additional());
  public function isMobile(){
    return $this->_is_mobile($this->_useragent);
  public function testAgent($ua){
    return $this->_is_mobile(strtolower($ua));
  public function fullRedirect($b = true){
    $this->_full_redirect = $b;
  public function getAgent(){
    return $this->_useragent;
  /**  Public Static Methods  **/
  public static function Redirect($redirect,$fullRedirect=false){
    $o = new self($redirect, $fullRedirect);
  public static function Mobile(){
      $o = new self('');
      self::$dmd = $o->isMobile();
      return self::$dmd;
      return self::$dmd;

Just in case anyone wants it.

Gitlez, the snipplet I posted is, as I said “an extemely simple way to detect mobile browser”, and the only snipplet 99% of what this community needs.
And if I wanted, I could just go and search for “php mobile browser detection” or w/e on google andfind it.
But what do you learn by copying and pasting a code? And do people really want to optimize their website for a billion different devices, or the top10 devices that most people use for web surfing?

Maybe strstr() isn’t the best way to detect a string within a string, but if my code returns TRUE, then I know it is a mobile browser, wether the code is the best ever made or if it is the worst ever made.

I could just aswell do something like:

$mobiles = array("mobile","android");
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);

foreach($mobiles as $mobile) {
 if(strpos($agent, $mobile) !== false) {
  $i += 1; // I have tested it with a loop of 10, 50, 100 and 1000 that $i += 1 is faster than $i++
if($i >= 1) {
  echo "You are using a mobile browser.";

Sure it still isn’t the best code, but it gets the job done, and all you have to do if you find another browser agent, just add it to the array.

I could find every single code I ever needed to build a website on the internet, but what is the fun with it if you just do “Can you give me the code?” in stead of doing some research and acctually gets the code done for yourself?

Well the reality is that I did write the class I provided. As someone who provides a “Premium” scripting site, you are opening yourself up to comments about the scripts you provide.

But what do you learn by copying and pasting a code?

Again, you are offering everyone to copy and paste your code, as well as that is the purpose of your site…

Further more, your second example would produce a ‘Notice’ Error. While you are correct that $i += 1 is marginally quicker than $i++, $i++ is quicker to type, and the differences are marginal. If you are worried about that marginal difference, than you will actually get more out of using ++$i than $i += 1;

And do people really want to optimize their website for a billion different devices, or the top10 devices that most people use for web surfing?

Really?!?.. You only need to optimize for mobile devices as a whole, not the individual devices. The irony of your scripts, is that they will only catch the mobile devices best equipped to view your ‘standard’ site, leaving the devices that most need a ‘mobile’ version to suffer through the standard site.



Returns true if a mobile device of false otherwise.

Apparently though, you consider %68 effectiveness, “getting the job done”.

I was simply adding my script so that others could then see another option.

If you can make my script better, then go for it. I am always looking to learn something new and improve my skills. I do not profess to know everything or even believe it on occasion.

What I know, I know. What I want to know is what I don’t know.

Now when people come to this Thread they will then have three options of how they want to address this issue. That is the underlining spirit of PHP; There is always another way of doing it. The option chosen depends on the circumstance and knowledge of the one implementing it.

I get frustrated when I see snippets that propagate bad techniques/practices. Even more frustrated when people think that a particular option is “99% of what this community needs”, you have them here, why not educate them a little more than the bare minimum. I appologize if you take offense to someone trying to show alternate methods.

NOTE strstr() is one of my biggest pet peeves, I apologize as it probably got me “going” a little more than a normal snippet would have. Another pet peeve is people using RegEx when they are not needed/optimal. Glad to see you’re not spreading that one.

so, ok we can detect if a person is using mobile web browser,

but what is a use of that? how can we benefit it from using on our websites

you could redirect mobile users to a more simplefied version of your website, or a mobile version if you want, and thus you could make the loading speed better for the mobile user.
But ofcourse, it is possible to make a JS script to detect the screen resolution and change the theme according to that aswell.

Anyway, I’d mainly use it to redirect users to a mobile website, so they save bandwidth if they e.g. have a limited XX MB dataplan.

Reading up about this - there is a css3 selector that can target devices of a certain screen size
eg '@media screen and (max-width < 400px) {…} chech out ‘CSS 3 media queries’.