Detect Mobile Device using Mobile-Detect Library in PHP

There might be cases when we want to hide the part of content or display different content on mobile devices. Usually, we apply different rules for different devices on the client side but sometimes we need to do this on the server side too.

Mobile-Detect is a PHP library that allows to detect mobile devices. This library is based on User-Agent request header combined with other specific HTTP headers.

Add Mobile-Detect library to composer.json file:

"require": {
    "mobiledetect/mobiledetectlib": "^2.8"
}

Install library from the command line:

composer install

We have created an instance of MobileDetect class. The isMobile method returns true if any type of mobile device is detected. If you want to detect only tablet devices you can use isTablet method. Mobile-Detect library also provides methods to detect specific operating systems such as Android or iOS.

<?php

use Detection\MobileDetect;

require_once __DIR__.'/vendor/autoload.php';

$detect = new MobileDetect();

if ($detect->isMobile()) {
    echo 'Mobile device';
}

if ($detect->isTablet()) {
    echo 'Tablet';
}

if ($detect->isAndroidOS()) {
    echo 'Android';
}

if ($detect->isiOS()) {
    echo 'iOS';
}

Leave a Comment

Your email address will not be published. Required fields are marked *