HOWTO · PHP

How to Detect Mobile Devices in PHP

Learn to classify mobile requests in PHP with Mobile Detect or a user-agent pattern.

On this page

In PHP, you can classify a request as mobile with the Composer-installed mobiledetect library or by matching HTTP_USER_AGENT from $_SERVER with preg_match(). Both methods infer a device category from request headers; neither can prove what physical device made the request.

Use the mobiledetect Class to Detect Mobile Devices in PHP

Install the mobiledetect library in your project with Composer using composer require mobiledetect/mobiledetectlib. Then load Composer’s vendor/autoload.php and create a Mobile_Detect instance. The library uses request information, including user-agent strings and other headers, to classify clients.

For a basic mobile check, call $detect->isMobile(). It returns a boolean that you can use in an if/else branch to choose the mobile or non-mobile result. The class also provides isTablet() when your application needs to treat tablets separately; decide how tablet results should affect your layout or feature before using the broader mobile classification.

This classification reflects the request received by PHP. A browser’s responsive design mode may send a different user-agent when you change its emulated device, but that does not verify behavior on every physical phone or tablet. User-agent values can be changed, and client detection should not be used as a security or identity check.

Use HTTP_USER_AGENT and the preg_match() Function to Detect Mobile Devices in PHP

For a dependency-free check, read HTTP_USER_AGENT from the $_SERVER superglobal and match it against a short set of mobile-related terms. The key may be absent, so provide a string fallback before calling preg_match(). This example checks a sample iPhone user-agent value; in a web request, PHP supplies the value from the request header.

<?php
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$pattern = '/(android|iphone|ipod|ipad|mobile|tablet)/i';
$isMobile = preg_match($pattern, $userAgent) === 1;

echo $isMobile ? 'Mobile device detected' : 'Mobile device not detected';

preg_match() returns 1 for a match, 0 when there is no match, and false if the pattern cannot be evaluated. The comparison with === 1 makes the branch depend only on a positive match. When a real request omits the header, the fallback is an empty string and this pattern produces the non-mobile branch.

Treat this result as a rough classification. User-agent strings can be absent, altered, or changed, and a short manually maintained pattern can miss newer or uncommon clients. A longer list is not a guarantee of complete coverage. The Stack Overflow discussion about mobile user-agent strings is a community-maintained reference, so review suggestions carefully before adapting them to your application.