Free Web Hosting Forum
Go Back   Free Web Hosting Forum > Website Building > Scripts and Code Snippets
Reload this Page PHP: Extremely simple way to check if it is a Mobile Browser
Reply
 
Thread Tools Display Modes
(#1)
Old
Leder678's Avatar
Leder678 Leder678 is offline
Senior Member
Leder678 is on a distinguished road
 
Posts: 1,817
Join Date: Jan 2009
Location: Norway
Default PHP: Extremely simple way to check if it is a Mobile Browser - 12-08-2011, 09:42 AM

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.

*CHECKED:
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.

PHP Code:
<?php
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
   echo 
"You are running a mobile webbrowser!";
}

IF YOU HAVE A MOBILE WITH A WEBBROWSER, COULD YOU PLEASE VISIT duppeditt.connlin.com/mobile.php AND PASTE THE FIRST LINE (SMILAR TO THE CODE BELOW) IN THIS TOPIC?

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


Follow me on twitter @Mortenrb

W3Fools - Read and learn

Please AT LEAST read the 10 bolded lines of the TOS at:
http://www.000webhost.com/includes/tos.php

Last edited by Leder678; 12-08-2011 at 01:13 PM.
Reply With Quote
(#2)
Old
Sogo7 Sogo7 is offline
Banned
Sogo7 is on a distinguished road
 
Posts: 294
Join Date: Dec 2010
Default 12-08-2011, 06:00 PM



To make things a little easier here's the QR code of that url.
Reply With Quote
(#3)
Old
Leder678's Avatar
Leder678 Leder678 is offline
Senior Member
Leder678 is on a distinguished road
 
Posts: 1,817
Join Date: Jan 2009
Location: Norway
Default 12-09-2011, 07:00 AM

Thanks, I didn't think about that
I'd karma you, but the karma button is beeing a bitch right now...


Follow me on twitter @Mortenrb

W3Fools - Read and learn

Please AT LEAST read the 10 bolded lines of the TOS at:
http://www.000webhost.com/includes/tos.php
Reply With Quote
(#4)
Old
lobrc's Avatar
lobrc lobrc is offline
Administrator
lobrc will become famous soon enough
 
Posts: 5,112
Join Date: Jan 2010
Default 12-09-2011, 03:27 PM

From my BB 9300:
Code:
Mozilla/5.0 (BlackBerry; U; BlackBerry 9300; en-GB) AppleWebKit/534.8+
(KHTML, like Gecko) Version/6.0.0.570 Mobile Safari/534.8+
Mobile Browser


Quote:
Originally Posted by Leder678 View Post
I'd karma you, but the karma button is beeing a bitch right now...
What's up with it?


If you're having problems with your account, please submit a ticket from your members area.

--

Free Script Installation Service
Reply With Quote
(#5)
Old
Leder678's Avatar
Leder678 Leder678 is offline
Senior Member
Leder678 is on a distinguished road
 
Posts: 1,817
Join Date: Jan 2009
Location: Norway
Default 12-10-2011, 10:36 AM

Okay, your BB is fine

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


Follow me on twitter @Mortenrb

W3Fools - Read and learn

Please AT LEAST read the 10 bolded lines of the TOS at:
http://www.000webhost.com/includes/tos.php
Reply With Quote
(#6)
Old
Gitlez's Avatar
Gitlez Gitlez is offline
Member
Gitlez is on a distinguished road
 
Posts: 76
Join Date: Nov 2011
Location: Canada
Default 12-11-2011, 08:20 AM

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 php.net page.

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

PHP Code:
<?php

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

    The user requested http://yoursite.com/Some/Page/ and was redirected to http://mobile.yoursite.com/Some/Page

*  ** 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(){
    if(
$this->_full_redirect){
      
$uri trim($_SERVER['REQUEST_URI'], '/');
      return (isset(
$uri{0}))? ((substr($this->_redirect, -11) === '/')? '' '/') . $uri '';
    }else{
      return 
NULL;
    }
  }
  
  
/**  Public Methods  **/
  
public function detectAndRedirect(){
    if(
$this->_is_mobile($this->_useragent) && strlen(trim($this->_redirect,'/')) > 0){
      if(
headers_sent()){
        echo 
'<meta http-equiv="refresh" content="0; url=' $this->_redirect $this->_additional() . '">';
      }else{
        
header('Location: ' $this->_redirect $this->_additional());
      }
      exit;
    }
  }
  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);
    
$o->detectAndRedirect();
  }
  public static function 
Mobile(){
    if(
is_null(self::$dmd)){
      
$o = new self('');
      
self::$dmd $o->isMobile();
      unset(
$o);
      return 
self::$dmd;
    }else{
      return 
self::$dmd;
    }
  }
}

Just in case anyone wants it.


Cheers,
Gitlez

Last edited by Gitlez; 12-11-2011 at 08:32 AM.
Reply With Quote
(#7)
Old
Leder678's Avatar
Leder678 Leder678 is offline
Senior Member
Leder678 is on a distinguished road
 
Posts: 1,817
Join Date: Jan 2009
Location: Norway
Default 12-11-2011, 03:50 PM

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:

PHP Code:
<?php
$mobiles 
= array("mobile","android");
$agent strtolower($_SERVER['HTTP_USER_AGENT']);
$i;

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?


Follow me on twitter @Mortenrb

W3Fools - Read and learn

Please AT LEAST read the 10 bolded lines of the TOS at:
http://www.000webhost.com/includes/tos.php
Reply With Quote
(#8)
Old
Gitlez's Avatar
Gitlez Gitlez is offline
Member
Gitlez is on a distinguished road
 
Posts: 76
Join Date: Nov 2011
Location: Canada
Default 12-11-2011, 07:27 PM

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.
Quote:
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;

Quote:
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.



PHP Code:
<?php

DetectMobileDevice
::Mobile();
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.


Cheers,
Gitlez

Last edited by Gitlez; 12-11-2011 at 11:19 PM.
Reply With Quote
(#9)
Old
tittbit tittbit is offline
Junior Member
tittbit is on a distinguished road
 
Posts: 12
Join Date: Feb 2012
Default 08-01-2012, 11:30 PM

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
Reply With Quote
(#10)
Old
Leder678's Avatar
Leder678 Leder678 is offline
Senior Member
Leder678 is on a distinguished road
 
Posts: 1,817
Join Date: Jan 2009
Location: Norway
Default 08-06-2012, 03:25 PM

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.


Follow me on twitter @Mortenrb

W3Fools - Read and learn

Please AT LEAST read the 10 bolded lines of the TOS at:
http://www.000webhost.com/includes/tos.php
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump



Powered by vBulletin® Version 3.8.2
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
vBulletin Skin developed by: vBStyles.com