PHP - Check If the Page Run on Mobile or Desktop Browser

Simplest way to detect a mobile device in PHP

Here is a source:

  • Detect Mobile Browser
  • Download PHP script

Code:

<?php

$useragent=$_SERVER['HTTP_USER_AGENT'];

if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||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|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(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|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))

header('Location: http://detectmobilebrowser.com/mobile');

?>

PHP - Check if the page run on Mobile or Desktop browser

There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net

Using that it's quite easy to only display content for a mobile:

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

// Check for any mobile device.
if ($detect->isMobile()){
// mobile content
}
else {
// other content for desktops
}

Detect Mobile or Windows PHP

Case 1 : Redirecting a site to a mobile version

Say we have a normal website that we need to redirect to a mobile version if viewed from a mobile device. All the code required for mobile detection is in a single file ‘Mobile_Detect.php’, which we can include in our web pages or in the primary index file. To simplify discussion let us assume you have a website ‘example1.com’ with a single index file, and need to redirect to ‘mobile.example1.com’ if a mobile device is detected. We need to put the following in the header of the index file of ‘example1.com’.

/* Change path info depending on your file locations */
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

if($detect->isMobile()) {
header('Location: http://mobile.example1.com/');
exit;
}

Case 2: Loading different resources depending on the device

We can load or modify existing content based on the users device profile. For example we could load a different CSS for a mobile or a tablet.

$detect = new Mobile_Detect;

if($detect->isMobile() || $detect->isTablet()) {
echo "<link rel='stylesheet' href='mobile.css type='text/css' />";
} else {
echo "<link rel='stylesheet' href='style.css type='text/css' />";
}

you can also user Javascript:

<script type="text/javascript">
<!--
if (screen.width <= 800) {
window.location = "http://m.domain.com";
}
//-->
</script>

or

You can use a .htaccess redirect to transfer visitors based upon the MIME types the browser supports. For example, if the user's browser accepts mime types that include WML (Wireless Markup Language), then most likely it is a mobile device.

The code below should be placed in your .htaccess file:

RewriteEngine On
# Check for mime types commonly accepted by mobile devices
RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^ http://m.domain.com%{REQUEST_URI} [R,L]

If youve got 2 sites one for each device (not the best thing to do here) you can have a index.php file on the root with :

<script type="text/javascript">
<!--
if (screen.width <= 800) {
window.location = "http://your.domain.com/mobile";
} else { window.location = "http://your.domain.com/desktop"; }
//-->
</script>

How to determine if the device is Mobile or Desktop?

Have you actually tried to use the project you discovered. I'd say that server side mobile detection IS a huge task with plenty of detail checks to ensure the correct outcome.

And using this class is completely easy. From the example directory:

require_once '../Mobile_Detect.php';
$detect = new Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');

Now you have a variable with one of three values: "tablet", "phone" or "computer", and you can react to this.

Please note that even if you are able to use this library without Composer, it will be updated regularly (as in "once every month"), because new devices get on the market and need to be detected. You will have to update this library at some point. Using Composer makes this very easy.

Reliable Way to Detect Desktop vs. Mobile Browser

What a little Google search turned up, from A Beautiful Site:

var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};

if(isMobile.any()){
// Mobile!
} else {
// Not mobile
}

I will not argue that feature detection is way preferable to user-agent sniffing, which is terrible actually. But if you're detecting feature to determine whether or not the device is considered mobile or not, you're exposing yourself to a whole new serie of problems.

You can't check pixel-ratio because new desktops computers will most likely be "retina" or super-HD. You can't check device-orientation because it's not something unique to mobiles anymore. You can't check (if you can) the gyroscope because some laptop might return values.

Build websites that works on all platforms without trying to separate them!

Detect mobile browser

Have my user agent code:

<?php

/* USER-AGENTS
================================================== */
function check_user_agent ( $type = NULL ) {
$user_agent = strtolower ( $_SERVER['HTTP_USER_AGENT'] );
if ( $type == 'bot' ) {
// matches popular bots
if ( preg_match ( "/googlebot|adsbot|yahooseeker|yahoobot|msnbot|watchmouse|pingdom\.com|feedfetcher-google/", $user_agent ) ) {
return true;
// watchmouse|pingdom\.com are "uptime services"
}
} else if ( $type == 'browser' ) {
// matches core browser types
if ( preg_match ( "/mozilla\/|opera\//", $user_agent ) ) {
return true;
}
} else if ( $type == 'mobile' ) {
// matches popular mobile devices that have small screens and/or touch inputs
// mobile devices have regional trends; some of these will have varying popularity in Europe, Asia, and America
// detailed demographics are unknown, and South America, the Pacific Islands, and Africa trends might not be represented, here
if ( preg_match ( "/phone|iphone|itouch|ipod|symbian|android|htc_|htc-|palmos|blackberry|opera mini|iemobile|windows ce|nokia|fennec|hiptop|kindle|mot |mot-|webos\/|samsung|sonyericsson|^sie-|nintendo/", $user_agent ) ) {
// these are the most common
return true;
} else if ( preg_match ( "/mobile|pda;|avantgo|eudoraweb|minimo|netfront|brew|teleca|lg;|lge |wap;| wap /", $user_agent ) ) {
// these are less common, and might not be worth checking
return true;
}
}
return false;
}

?>

How to use:

<?php
$ismobile = check_user_agent('mobile');
if($ismobile) {
return 'yes';
} else {
return 'no';
}
?>

How to know site open in mobile or PC browser?

with CSS you can use @media-queries like the following:

@media screen and (max-width: 1199px) {
.your-navigation{
display:none;
}
}

or you use jQuery like the following:

if($(window).width()<=1199){
$(".your-navigation").hide();
}

but i would go with media queries, because its a more elegant and more easy to change way!

so actually you are not checking if its a mobile browser or desktop, but its totally okay, to check the width of the browser... i think, thats more what you want...

** edit **

after some thoughts i just wanna say, that it is possible to get the current browser by using javascript, but i wouldn't recommend that to you, because its not rubust and you will have a lot of pain with getting all browsers and so on... as i already said, go with the width! :)

(here is a link with an approach)

** edit 2 **

regarding your comment:

check this link out, it should be exactly what you want

here the code, thanks to feeela

/**
* Determine the mobile operating system.
* This function either returns 'iOS', 'Android' or 'unknown'
*
* @returns {String}
*/
function getMobileOperatingSystem() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;

if( userAgent.match( /iPad/i ) || userAgent.match( /iPhone/i ) || userAgent.match( /iPod/i ) )
{
return 'iOS';

}
else if( userAgent.match( /Android/i ) )
{

return 'Android';
}
else
{
return 'unknown';
}
}

Detect Only Mobile Users with Desktop Mode Browsers

On Android Chrome, "Desktop Mode" removes the "Android" string from the user agent. If you can use JavaScript, the following mostly detects Android Chrome Desktop Mode:

var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.appVersion)[1], 10); // also matches AppleWebKit
var isGoogle = webkitVer && navigator.vendor.indexOf('Google') === 0; // Also true for Opera Mobile and maybe others
var isAndroid = isGoogle && userAgent.indexOf('Android') > 0; // Careful - Firefox and Windows Mobile also have Android in user agent
var androidDesktopMode = !isAndroid && isGoogle && (navigator.platform.indexOf('Linux a') === 0) && 'ontouchstart' in document.documentElement;

It makes the assumption that Chrome with an ARM processor is Android. The assumption definitely fails for users running Linux on ARM, fails for Android on i686 or MIPS etc (and I haven't been able to test ChromeOS).

For Windows Mobile, you can detect desktop mode by checking for the string "WPDesktop;" in the user agent.

Edit: The code used to use window.chrome and window.chrome.webstore which was a reliable test, but somewhere around Chrome 65 you couldn't use those properties anymore to detect desktop mode. Thanks to @faks for the info.

Edit 2: I now highly recommend against treating "desktop mode" as "mobile mode" but, here are my updated opinions:

  • beware that code detecting desktop mode is really fragile and newer browser versions regularly break sniffing code techniques

  • unless you have a serious bug or critical usability issue, it totally isn't worth sniffing

  • never sniff if you are not actively maintaining the code and testing against beta versions of browsers

  • I use the following for iOS: navigator.vendor.indexOf('Apple') === 0 && 'ontouchstart' in document.body. We need this to set the astonishingly shitty iOS inputMode correctly for iPadOS 13 (old navigator.platform technique now broken in iOS 13 Beta) and avoid other iOS usability bugs with other input types. I think you can check window.screen.width == 768 to sniff iPad (stays same even if orientation change). The sniff will break if Macbook comes out in a touch version.

  • I now use the following for detecting Android desktop mode: 'ontouchstart' in document.body && navigator.platform.indexOf('Linux a') === 0 && (window.chrome || (window.Intl && Intl.v8BreakIterator)). Horrible unreliable sniff, but we really need it because android viewport and pinch zooming (not page zooming) is really broken on Android for our SPA (screen size is not enough as a desktop touch user can use a small window).



Related Topics



Leave a reply



Submit