Table of Contents
Using the HTTP_USER_AGENT and preg_match() functions in PHP Detecting Mobile Devices
Home Backend Development PHP Tutorial Detect mobile devices with PHP

Detect mobile devices with PHP

Feb 28, 2024 pm 12:01 PM
iphone php programming Backend Development Mobile terminal adaptation

php Xiaobian Yuzai today introduces how to use PHP to detect mobile devices. With the popularity of mobile devices, responsive design of websites has become particularly important. By detecting the type of device used by users to access the website through PHP, we can provide customized content and layout for different devices to improve user experience. This article will introduce how to use PHP to detect the user's device type and provide better mobile adaptation for your website.


To detect mobile devices using the mobiledetect class in php

we can use the class named Mobile Detect Lightweight PHP class to detect mobile devices in PHP. It can also detect tablet devices. The library uses certain Http headers and user-agent strings to detect mobile devices. We can download the library using Composer using the following command.

<code><code class="bash hljs" data-lang="bash"><span style="display:flex;"><span>composer require mobiledetect/mobiledetectlib
</span></span></code></code>
Copy after login

This library provides various methods, such as isMobile(), isTablet(), is<strong class="keylink">iOS</strong>() to detect various mobile environments. We can create objects of class Mobile_Detect() and use these methods.

For example, use the composer command above to download the library in the project directory. Next, the file autoload.php is required using the require_once function. This file is located in the vendor directory. Next, create an object of class Mobile_Detect() $detect. Then, use the function isMobile() under the if condition. In the if block, display the message Mobile device detected, and in the else block display the message Mobile device not detected .

The following example will detect whether a web page is accessed from a mobile device. The output section below shows what happens when a web page is opened from a PC. We can inspect the element by right-clicking on the web page to find Responsive Design Mode. There we can select a different mobile device and refresh the script. When we select mobile device, the output will change to Mobile device detected. In this way, we can use the Mobile Detect class to detect mobile devices in PHP.

Sample code:

<code><code class="php hljs" data-lang="php"><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">require_once</span> <span style="color:#ba2121">"vendor/autoload.php"</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#19177c">$detect</span> <span style="color:#666">=</span> <span style="color:#008000;font-weight:bold">new</span> Mobile_Detect;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">if</span> ( <span style="color:#19177c">$detect</span><span style="color:#666">-></span><span style="color:#7d9029">isMobile</span>() ) {
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">echo</span> <span style="color:#ba2121">"Mobile device detected"</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">else</span> {
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">echo</span> <span style="color:#ba2121">"Mobile device not detected"</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span><span style="color:#bc7a00">?></span><span >
</span></span></span></code></code>
Copy after login

Output:

<code><code class="text hljs" data-lang="text"><span style="display:flex;"><span>Mobile device not detected
</span></span></code></code>
Copy after login

Using the HTTP_USER_AGENT and preg_match() functions in PHP Detecting Mobile Devices

We can use the string HTTP_USER_AGENT to get information about the website visited by the user's browser. We will use the $_SERVER superglobal variable and the string as the array element. Superglobal variables contain information about the NetworkServer. We will create a custom collection of user-agent strings found on mobile devices. We can then use the preg_match() function to check if these match the browser the current user is browsing. As new supported mobile devices are released, collections of user-agent strings can be added manually. An updated list of user agent string collections can be found here.

For example, create a variable $user_agent and store $_SERVER["HTTP_USER_AGENT"] in it. Then use the preg_match() function to match the user agent string. Use a collection of strings as the first argument. Use the $user_agent variable as the second parameter. Finally, use the if-else condition to display the message accordingly.

Here, we opened the web page from the iPhone. So the user agent string matches the set. This way, we can detect mobile devices in PHP.

Sample code:

<code><code class="php hljs" data-lang="php"><span style="display:flex;"><span><span style="color:#19177c">$user_agent</span> <span style="color:#666">=</span> <span style="color:#19177c">$_SERVER</span>[<span style="color:#ba2121">"HTTP_USER_AGENT"</span>];
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">if</span>(preg_match(<span style="color:#ba2121">"/(<strong class="keylink">Android</strong>|<strong class="keylink">WEB</strong>os|avant<strong class="keylink">Go</strong>|iphone|ipod|ipad|bolt|boost|cricket|docomo|fone|hiptop|opera mini|mini|kitkat|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i"</span>,<span style="color:#19177c">$user_agent</span> ))
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">echo</span> <span style="color:#ba2121">"mobile device detected"</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">else</span>{
</span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">echo</span> <span style="color:#ba2121">"mobile device not detected"</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></code>
Copy after login

Output:

<code><code class="text hljs" data-lang="text"><span style="display:flex;"><span>Mobile device detected
</span></span></code></code>
Copy after login

The above is the detailed content of Detect mobile devices with PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

iPhone 16 Pro and iPhone 16 Pro Max official with new cameras, A18 Pro SoC and larger screens iPhone 16 Pro and iPhone 16 Pro Max official with new cameras, A18 Pro SoC and larger screens Sep 10, 2024 am 06:50 AM

Apple has finally lifted the covers off its new high-end iPhone models. The iPhone 16 Pro and iPhone 16 Pro Max now come with larger screens compared to their last-gen counterparts (6.3-in on the Pro, 6.9-in on Pro Max). They get an enhanced Apple A1

iPhone parts Activation Lock spotted in iOS 18 RC — may be Apple\'s latest blow to right to repair sold under the guise of user protection iPhone parts Activation Lock spotted in iOS 18 RC — may be Apple\'s latest blow to right to repair sold under the guise of user protection Sep 14, 2024 am 06:29 AM

Earlier this year, Apple announced that it would be expanding its Activation Lock feature to iPhone components. This effectively links individual iPhone components, like the battery, display, FaceID assembly, and camera hardware to an iCloud account,

iPhone parts Activation Lock may be Apple\'s latest blow to right to repair sold under the guise of user protection iPhone parts Activation Lock may be Apple\'s latest blow to right to repair sold under the guise of user protection Sep 13, 2024 pm 06:17 PM

Earlier this year, Apple announced that it would be expanding its Activation Lock feature to iPhone components. This effectively links individual iPhone components, like the battery, display, FaceID assembly, and camera hardware to an iCloud account,

Gate.io trading platform official app download and installation address Gate.io trading platform official app download and installation address Feb 13, 2025 pm 07:33 PM

This article details the steps to register and download the latest app on the official website of Gate.io. First, the registration process is introduced, including filling in the registration information, verifying the email/mobile phone number, and completing the registration. Secondly, it explains how to download the Gate.io App on iOS devices and Android devices. Finally, security tips are emphasized, such as verifying the authenticity of the official website, enabling two-step verification, and being alert to phishing risks to ensure the safety of user accounts and assets.

Multiple iPhone 16 Pro users report touchscreen freezing issues, possibly linked to palm rejection sensitivity Multiple iPhone 16 Pro users report touchscreen freezing issues, possibly linked to palm rejection sensitivity Sep 23, 2024 pm 06:18 PM

If you've already gotten your hands on a device from the Apple's iPhone 16 lineup — more specifically, the 16 Pro/Pro Max — chances are you've recently faced some kind of issue with the touchscreen. The silver lining is that you're not alone—reports

Anbi app official download v2.96.2 latest version installation Anbi official Android version Anbi app official download v2.96.2 latest version installation Anbi official Android version Mar 04, 2025 pm 01:06 PM

Binance App official installation steps: Android needs to visit the official website to find the download link, choose the Android version to download and install; iOS search for "Binance" on the App Store. All should pay attention to the agreement through official channels.

How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? Mar 31, 2025 pm 11:51 PM

Problem Description When calling Alipay EasySDK using PHP, after filling in the parameters according to the official code, an error message was reported during operation: "Undefined...

Download link of Ouyi iOS version installation package Download link of Ouyi iOS version installation package Feb 21, 2025 pm 07:42 PM

Ouyi is a world-leading cryptocurrency exchange with its official iOS app that provides users with a convenient and secure digital asset management experience. Users can download the Ouyi iOS version installation package for free through the download link provided in this article, and enjoy the following main functions: Convenient trading platform: Users can easily buy and sell hundreds of cryptocurrencies on the Ouyi iOS app, including Bitcoin and Ethereum. and Dogecoin. Safe and reliable storage: Ouyi adopts advanced security technology to provide users with safe and reliable digital asset storage. 2FA, biometric authentication and other security measures ensure that user assets are not infringed. Real-time market data: Ouyi iOS app provides real-time market data and charts, allowing users to grasp encryption at any time

See all articles