How to Detect Mobile Device in PHP

Recently while working on a client’s project, we came across a situation where we need to display different sliders on a website for desktop and mobile. You may be looking for the same scenario for your projects. If yes then keep reading. In this article, I show you how to detect a mobile device in PHP.

There are certain scenarios where we hide the part of the website content on mobile. Normally, we use media queries and apply rules for different devices. The media queries work on the client-side. But sometimes, we need to apply conditions at the server-side for mobile devices.

For instance, you are planning to build a different website for mobile users. When a user visits your URL you wanted to redirect them to your mobile website. This is the one example where we want to detect mobile devices at the server-side. There may be hundreds of cases. In my case, it was a different slider for desktop and mobile devices.

That being said, let’s take a look at how to detect a mobile device in PHP.


To handle the mobile detection, one nice library available on the GitHub which is Mobile-Detect.

This library provides a very clean and easy way to find out if the user is on a mobile device.

For installation of this library, I recommend to use Composer. Open the terminal in your project root directory and run the command below:

composer require mobiledetect/mobiledetectlib

If you don’t want to use Composer then alternate way is include this Mobile_Detect.php file in your project.

Detect Mobile Device in PHP

If you have installed the library using the Composer then add the below statement at the top of your file.

require_once "vendor/autoload.php";

After this, just create the instance of Mobile_Detect class and you are able to find out if your visitor is on a mobile device.

$detect = new Mobile_Detect;

if ( $detect->isMobile() ) {
    echo "You are on the mobile device.";
} else {
    echo "You are on desktop.";

That’s it! You are done. This is the easiest way to detect a mobile device in PHP. Let me know your thoughts and suggestions in the comment section below.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “How to Detect Mobile Device in PHP

Leave a Reply

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