Detect Mobile Devices in PHP
PHP can detect whether a visitor is using a mobile device by inspecting the User-Agent HTTP header. This lets you redirect mobile users to a mobile-optimised page or serve different content based on the device type.
Examples
A lightweight function that checks the User-Agent string against a pattern of known mobile browser signatures:
<?php
function isMobile() {
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
$mobileKeywords = [
'android', 'iphone', 'ipod', 'blackberry', 'opera mini',
'windows phone', 'palm', 'symbian', 'mobile'
];
foreach ($mobileKeywords as $keyword) {
if (strpos($userAgent, $keyword) !== false) {
return true;
}
}
return false;
}
// Usage: redirect mobile users
if (isMobile()) {
header('Location: https://m.example.com' . $_SERVER['REQUEST_URI']);
exit;
}
?>
The function accepts the following detection targets, which you can enable or disable:
- iPhone / iPod — set to
trueto treat as mobile, or provide a redirect URL. - Android — set to
trueto treat Android handsets as mobile. - Opera Mini — set to
trueto treat as mobile. - BlackBerry — set to
trueto treat as mobile. - Windows Mobile — set to
trueto treat as mobile.
Notes
User-Agent detection is a heuristic and not 100% reliable — some desktop browsers spoof mobile UAs and vice versa. For new projects, prefer CSS media queries and responsive design over server-side detection. Reserve PHP detection for cases where you genuinely need to serve a fundamentally different page or redirect to a separate mobile domain.