Friday, September 5, 2025
HomeLanguagesHow to detect a mobile device using PHP?

How to detect a mobile device using PHP?

We often find it important to detect the browser of our user to provide a better display experience. Few websites are mandatory to be accessed from a PC and not from mobile. Also, it acts as a precautionary measure for careless users to fill important forms from a smaller display like that of mobile.

Using HTTP_USER_AGENT: We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP.

Syntax:

$_SERVER['HTTP_USER_AGENT']

.

Here the $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. These special variables were introduced in PHP 4.1.0. Next we need to read the message returned by the HTTP_USER_AGENT to pass the control to the next set of instructions. For demonstration purpose we will put an echo”” statement to confirm a mobile device is detected. We will read the HTTP_USER_AGENT’s returned message with preg_match() function. It performs a regular expression match.

Example: It’s easy to get lost in this huge chunk of regex but it’s like this to detect every sort of browser from every mobile Operating system available in the market(can also detect Kindle devices). For example, (android|bb\d+|meego).+mobile|avantgo|bada will check if the user device’s operating system is Android or not. If this snippet is inserted into the index.php of the website and the site is accessed from a mobile device, the browser will show the message as Mobile Browser Detected.




<?php
function isMobileDevice() {
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo
|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i"
, $_SERVER["HTTP_USER_AGENT"]);
}
if(isMobileDevice()){
    echo "Mobile Browser Detected";
}
else {
    echo "Mobile Browser Not Detected";
}
?>


Output: We are accessing it from a laptop.

Mobile Browser Not Detected
RELATED ARTICLES

Most Popular

Dominic
32267 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6635 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7026 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6720 POSTS0 COMMENTS