Categories
PHP

How to detect a user agent or device in PHP

In this tutorial we will see how you can check for a device or user agent using a third party script known as Mobile_Detect.php.

It is a lightweight PHP Class and can be integrated by downloading and requiring in your php script or can be installed via Composer.

For a quick integration, you can simply download the class from here:

https://github.com/serbanghita/Mobile-Detect/blob/master/Mobile_Detect.php

Below is a sample php script for testing whether the device or user agent is a Tablet, Desktop, Mobile etc.

<?php 
// Include and instantiate the class.
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
 
// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {
  echo "I am a mobile phone";
}
 
// Any tablet device.
if( $detect->isTablet() ){
  echo "I am a tablet";
}
 
// Exclude tablets.
if($detect->isMobile() && !$detect->isTablet() ){
  echo "I am  a mobile not a tablet";
}
 
if(!$detect->isMobile() && !$detect->isTablet() ){
  echo "I am neither a mobile nor a tablet";
}

// Check for a specific platform with the help of the magic methods:
if( $detect->isiOS() ){
  echo "I am on iOS"; 
}
 
if( $detect->isAndroidOS() ){
  echo "I am on Android"; 
}
 
 
// Batch mode using setUserAgent():
$userAgents = array(
'Mozilla/5.0 (Linux; Android 4.0.4; Desire HD Build/IMM76D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19',
'BlackBerry7100i/4.1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/103',
// [...]
);
foreach($userAgents as $userAgent){
 
  $detect->setUserAgent($userAgent);
  $isMobile = $detect->isMobile();
  $isTablet = $detect->isTablet();
  // Use the force however you want.
 
}
 
// Get the version() of components.
// WARNING: this method is in BETA, some keyword properties will change in the future.
if($detect->version('iPad'))
  echo "I am iPad: "; // 4.3 (float)

if($detect->version('iPhone'))
  echo "I am iPhone: " ; // 3.1 (float)

if($detect->version('Android'))
  echo "I am Android: " ; // 2.1 (float)

if($detect->version('Opera Mini'))
  echo "I am Opera Mini: "; // 5.0 (float)