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
- How to detect a mobile device in jQuery?
- How to detect the user's device using jQuery ?
- How to target desktop, tablet and mobile using Media Query ?
- How to disable zoom on a mobile web page using CSS?
- How to get daily weather notification on mobile using Node.js and Twilio API ?
- How to create responsive website zoomed out to full width on mobile using Bootstrap?
- How to Hide an HTML Element in Mobile View using jQuery ?
- How to design editable listview using jQuery Mobile plugin?
- How to design side navigation for mobile using Sidetap plugin ?
- How to design form controls for mobiles using jQuery Mobile BootstrapTheme plugin ?
- How to design form controls for mobiles using jQuery Mobile Square-UI Theme plugin ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.