Reliably Detect Mobile Browsers Server-Side

/, Snippets/Reliably Detect Mobile Browsers Server-Side

Reliably Detect Mobile Browsers Server-Side

Having a realiable mobile detection script running server side is a great way to show certaint website sections on mobile devices without having the actual content hidden from css. This is also a great way to improve page speed.

The script I’m going to use today is called Mobile Detect by Serban Ghita. It is a PHP Class which handles detection of devices and operating sysytems using the User-Agent string and HTTP headers to detect the environment.

I use it because Mobile Detect is reliable and it’s arround since 2009.

Installation and Set Up

Let’s start by downloading Mobile Detect from https://github.com/serbanghita/Mobile-Detect
What we actually need is the Mobile_Detect.php file. This is the file containing the PHP Class we wont be needing any of the other files inside the repository.
That said… Upload Mobile_Detect.php to your project. For this articles pourpouse lets say we will place it in /libs directory.

The last installation step is to actually include the file to our project.
Add require_once "libs/Mobile_Detect.php"; somwhere in the begining of your PHP file (preferably where your includes are declared)
and create a instance of the class using $detect = new Mobile_Detect;.

Basics

<?php
// Include Mobile Detect.
require_once 'Mobile_Detect.php';
//Instantiate class
$detect = new Mobile_Detect;
<?php
// Check for mobile environment. 
if ( $detect-&gt;isMobile() ) {
    // Your code here.
}
<?php
// Check for tablet device. 
if( $detect-&gt;isTablet() ) {
    // Your code here.
}
<?php
// Check operation system by using the magic methods:
if( $detect->isiOS() ) {
    // Your code here.
}

if( $detect->isAndroidOS() ) {
    // Your code here.
}
//Get the OS version
$detect->version('iPad'); // returns 4.3 (float)
$detect->version('iPhone') // returns 3.1 (float)
$detect->version('Android'); // returns 2.1 (float)
$detect->version('Opera Mini'); // returns 5.0 (float)

I think thats it, this script is very easy to work with.

Please let me know if you have any question in the comments below.

By | 2018-03-12T15:14:53+00:00 February 12th, 2017|PHP, Snippets|0 Comments

Leave A Comment