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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1654
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
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,

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

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.

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...

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.

iPhone 16 Pro Max lab test reveals its actual charging speed iPhone 16 Pro Max lab test reveals its actual charging speed Sep 19, 2024 am 06:15 AM

Some are criticizing the new iPhone 16 lineup due to lack of innovation, and as revealed by Ming-Chi Kuo, Apple has also received lower pre-orders than expected. The analyst noted that the sub-par pre-order volume is mainly due to the new phones not

How to view XML on your phone without a network How to view XML on your phone without a network Apr 02, 2025 pm 10:30 PM

There are two ways to view XML files: Android phones: use file manager or third-party applications (XML Viewer, DroidEdit). iPhone: Transfer files via iCloud Drive and use the Files app or third-party app (XML Buddha, Textastic).

Multi-party certification: iPhone 17 standard version will support high refresh rate! For the first time in history! Multi-party certification: iPhone 17 standard version will support high refresh rate! For the first time in history! Apr 13, 2025 pm 11:15 PM

Apple's iPhone 17 may usher in a major upgrade to cope with the impact of strong competitors such as Huawei and Xiaomi in China. According to the digital blogger @Digital Chat Station, the standard version of iPhone 17 is expected to be equipped with a high refresh rate screen for the first time, significantly improving the user experience. This move marks the fact that Apple has finally delegated high refresh rate technology to the standard version after five years. At present, the iPhone 16 is the only flagship phone with a 60Hz screen in the 6,000 yuan price range, and it seems a bit behind. Although the standard version of the iPhone 17 will have a high refresh rate screen, there are still differences compared to the Pro version, such as the bezel design still does not achieve the ultra-narrow bezel effect of the Pro version. What is more worth noting is that the iPhone 17 Pro series will adopt a brand new and more

See all articles