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.
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.
Output: We are accessing it from a laptop.
Mobile Browser Not Detected