Mobile_Detect is a lightweight PHP class for detecting mobile devices (including tablets). It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.

Last update: Jun 28, 2022

Mobile Detect

Motto: "Every business should have a detection script to detect mobile readers."

Build status Latest Stable Version Total Downloads Daily Downloads License Chat on Slack

About

Mobile Detect is a lightweight PHP class for detecting mobile devices (including tablets). It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.

Why

Your website's content strategy is important! You need a complete toolkit to deliver an experience that is optimized, fast and relevant to your users. Mobile Detect class is a server-side detection tool that can help you with your RWD strategy, it is not a replacement for CSS3 media queries or other forms of client-side feature detection.

How

We're committed to make Mobile_Detect the best open-source mobile detection resource and this is why before each release we're running unit tests and research and update the detection rules on monthly basis.

Who

See the history of the project.

Announcements

  • JetBrains is sponsoring the project by providing licenses for PHPStorm and DataGrip.
  • Mobile_Detect 2.x.x is only integrating new regexes, User-Agents and tests. We are focusing on new tablets only. The rest of the PRs about TVs, bots or optimizations will be closed and analyzed after 3.0.0-beta is released.
  • Mobile_Detect 3.x.x is experimental and WIP.

Install

Download and include manually

Use this to quickly test the demo.

require_once "libs/Mobile_Detect.php";

Install as a composer package

Use this method to get continuous updates.

composer require mobiledetect/mobiledetectlib

or include the dependency in the composer.json file:

{
    "require": {
        "mobiledetect/mobiledetectlib": "^2.8"
    }
}

Demo

Contribute

Submit a PR

Submit a pull request but before make sure you read how to contribute guide.

Donate

Paypal
Donate 👍

I'm currently paying for hosting and spend a lot of my family time to maintain the project and planning the future releases. I would highly appreciate any money donations that will keep the research going.

Special thanks to the community 👍 for donations, JetBrains team for the continuous support and Dragos Gavrila who contributed with the logo.

Modules, plugins, ports

Submit new module, plugin, port

👉 Keep Mobile_Detect.php class in a separate module and do NOT include it in your script core because of the high frequency of updates. 👉 When including the class into your web application or module always use include_once '../path/to/Mobile_Detect.php to prevent conflicts.

JavaScript

Varnish Cache

  • Varnish Mobile Detect - Drop-in varnish solution to mobile user detection based on the Mobile-Detect library. Made by willemk.
  • mobiledetect2vcl - Python script to transform the Mobile Detect JSON database into an UA-based mobile detection VCL subroutine easily integrable in any Varnish Cache configuration. Made by Carlos Abalde.

LUA

  • mobile-detect.lua is a port of Mobile-Detect to Lua for NGINX HTTP servers. Follows closely to mobile-detect.js. Supports all methods that server-side mobile-detect.js supports. Fully unit-tested and synced with Travis CI (Build Passing badge included). Made by Mark Walters.

PHP

WordPress

  • Mobile Detect for WordPress - WordPress has a built-in function (wp_is_mobile()) to detect mobile devices. There is (at least) one catch, though. It considers iPad (iPad pro, and any tablet) as a mobile. So, this 3rd party module changes the way wp_is_mobile() works with the help of Mobile Detect PHP library! Made by Pothi Kalimuthu

  • WordPress Mobile Detect - Gives you the ability to wrap that infographic in a [notdevice][/notdevice] shortcode so at the server level WordPress will decide to show that content only if the user is NOT on a phone or tablet. Made by Jesse Friedman.

  • mobble - provides mobile related conditional functions for your site. e.g. is_iphone(), is_mobile() and is_tablet(). Made by Scott Evans.

  • WordPress Responsage - A small WordPress theme plugin that allows you to make your images responsive. Made by Adrian Ciaschetti.

  • WP247 Body Classes - Add unique classes to the body tag for easy styling based on various attributes (archive, user, post, mobile) and various WordPress "is" functions. Mobile attributes include type of device, Operating System, Browser, etc. Examples: .is-mobile, .is-not-mobile, .is-tablet, .is-ios, .is-not-ios, .is-androidos, .is-chromebrowser. Made by wescleveland56.

  • Adaptive Content for WordPress provides the most intuitive set of shortcodes for including/excluding content on mobile devices, tablets desktops and other more specific device parameters. This lightweight plugin lets content writers and theme authors choose when WordPress should or shouldn’t show any give content item using shortcodes and quicktags or theme elements using functions. Made by AddFunc.

  • AddFunc Mobile Detect for WordPress redirects mobile traffic to your mobile website and, basically, gives you loads of control over your mobile redirects. Made by AddFunc.

Drupal

Joomla

  • yagendoo Joomla! Mobile Detection Plugin - Lightweight PHP plugin for Joomla! that detects a mobile browser using the Mobile Detect class. Made by yagendoo media.

  • User Agent Detector plugin - This system plugin detects the user agent of your website visitor and sets a session variable accordingly. Based on the user agent, the plugin detects if the site is running on a desktop pc, tablet or smartphone. It can also detect if the visitor is a spider bot (search engine). Session variable that is set: ualayout. Possible values: desktop, tablet, mobile, bot. Made by @ReneKreijveld.

Magento

PrestaShop

  • PrestaShop is a free, secure and open source shopping cart platform. Mobile_Detect is included in the default package since 1.5.x.

Laravel

  • Agent is a user agent class for Laravel based on Mobile Detect with some additional functionality. Made by Jens Segers.

  • Laravel Mobile Detect is a package that enables you to use device detection right in your Laravel Blade templates. (Utilises the well-known, constantly updated PHP mobile detection library.) Made by Barnabas Kecskes.

  • BrowserDetect is a browser and mobile detection package, collects and wrap together the best user-agent identifiers for Laravel. Created by Varga Zsolt.

Zend Framework

  • ZF2 Mobile-Detect is a Zend Framework 2 module that provides Mobile-Detect features (Mobile_Detect class as a service, helper for views and plugin controllers). Made by neilime.

  • ZF2 MobileDetectModule facilitates integration of a PHP MobileDetect class with some ZF2-based application. Has similar idea like the existing ZF2 Mobile-Detect module, but differs in initialization and provision routine of the actual Mobile_Detect class. Appropriate view helper and controller plugin also have different conceptions. Made by Nikola Posa.

Symfony

Slim Framework

  • Slim_Mobile_Detect implements Mobile_Detect lib for different responses write on Slim Framework App.

ExpressionEngine

Yii Framework

CakePHP

FuelPHP

  • Special Agent is a FuelPHP package which uses php-mobile-detect to determine whether a device is mobile or not. It overrides the Fuelphp Agent class its methods. Made by Robbie Bardjin.

TYPO3

  • px_mobiledetect is an extension that helps to detect visitor's mobile device class (if that’s tablet or mobile device like smartphone). Made by Alexander Tretyak.

Other

  • PageCache is a lightweight PHP library for full page cache, with built-in Mobile-Detect support. Made by Muhammed Mamedov.

  • Statamic CMS Mobile Detect is a plugin. Made by Sergei Filippov of Haiku Lab.

  • Kohana Mobile Detect is an example of implementation of Mobile_Detect class with Kohana framework. Written by Luiz Alberto S. Ribeiro.

  • MemHT is a Free PHP CMS and Blog that permit the creation and the management online of websites with few and easy steps. Has the class included in the core.

  • concrete5 is a CMS that is free and open source. The library is included in the core.

  • engine7 is PHP Open Source Framework. The Mobile_Detect class is included in the engine.

  • Zikula is a free and open-source Content Management Framework, which allows you to run impressive websites and build powerful online applications. The core uses Mobile-Detect to switch to a special Mobile theme, using jQueryMobile.

  • UserAgentInfo is a PHP class for parsing user agent strings (HTTP_USER_AGENT). Includes mobile checks, bot checks, browser types/versions and more. Based on browscap, Mobile_Detect and ua-parser. Created for high traffic websites and fast batch processing. Made by quentin389.

  • LJ Mobile Detect is a simple implementation of Mobile Detect for Craft CMS. Made by Lewis Jenkins.

  • Detect Craft is a Craft CMS wrapper for the Mobile_Detect library. Made by Mikkel Rummelhoff.

  • Grav Plugin Mobile Detect is a simple implementation of Mobile Detect for Grav CMS. Made by Dimitri Longo.

  • Mobile_Detect module for UliCMS. Made by derUli.

Perl

Python

  • pymobiledetect - Mobile detect python package. Made by Bas van Oostveen.

Ruby

  • mobile_detect.rb is a Ruby gem using the JSON data exposed by the php project and implementing a basic subset of the API (as much as can be done by the exposed data). Made by Karthik T.

Go

LUA

  • ua-lua is a small lib written in LUA providing device type detection. ua-lua is detecting mobile or tablet devices based on user-agent inside nginx daemon. Made by Frédéric Robinet.

.Net

ColdFusion

Experiments 💡

GitHub

https://github.com/serbanghita/Mobile-Detect
Comments
  • 1. [Wordpress] WP Cache + Mobile Detect

    Hello,

    Is there anyone interested in developing a plugin of Mobile Detect that works with WP Cache? I've heard about this before, but lately it was brought to my attention: https://twitter.com/petripottonen/status/413281101952466944

    Is this possible server-side?

    Reviewed by serbanghita at 2013-12-18 13:03
  • 2. performance benchmarks

    I have an idea but I'd like to discuss and see what everyone thinks.

    As we make improvements, I'd like to try to make some that are targeted at performance. There was some mention in #39 of performance hits and I'm interested in creating a benchmark that will help determine a baseline as well as what improvements (or lack thereof) are made in future versions.

    Here are some benchmarks I'm thinking of:

    1. Run a random subset of matches from the list of known user agents and do this over a period of runs. For example, suppose we have 500 user agents. Choose 50 of them and run the regex. Now repeat this 10 times and take the average time and memory consumed over all of these runs.
    2. Run the whole set of user agents checking each one for the usual isMobile and isTablet methods. Measure the time and memory consumed.

    In order to keep a level playing field, I'd create a tiny, small, or medium EC2 instance on AWS and always run the benchmarks on that instance. Given the virtualized environment, I'd need to run each benchmark enough times to allow for statistical significance despite performance variations in these virtualized environments.

    I'm basically looking for any ideas/suggestions.

    Reviewed by nicktacular at 2013-07-31 01:08
  • 3. Fatal error: Class 'Mobile_Detect' not found

    Hi,

    I am trying to implement this on a site.

    Currently i have included the following tag to an include file that shows up just after the body tag

    isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer'); ?> isMobile() && !$detect_headerads->isTablet()) { include("/home/xxx/public_html/inc/ads/mobile_32050.php") ; } else { include("/home/xxx/public_html/inc/ads/non_mobile_72890.php") ; } ?>

    Further down the page i have few other instances like this

    isMobile() && !$detectcats->isTablet()) { include("/home/xxx/public_html/inc/blank.php") ; } else { include("/home/xxx/public_html/inc/message.php"); } ?>

    My problem is.. I am trying to move the below code before or after or in the header so that i can load certain js files depending on whether its a mobile or not.

    isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer'); ?>

    But when i moved the above code to the header , i am getting the following error

    Fatal error: Class 'Mobile_Detect' not found in /home/xxx/public_html/inc/ads/header_ads.php on line 2

    Can you please help?

    btw, i was using 2.6.2 and just upgraded to 2.6.3

    Reviewed by spk100 at 2013-07-26 13:16
  • 4. Added a method to retrieve the array of mobile browsers and changed '->userAgents' to '->browsers' for clarity.

    Hi, I needed to get the ->userAgents array from outside of Mobile_Detect.php so I've added a method to retrieve it.

    Then however, you end up with: $md->getUserAgent(); $md->getUserAgents(); which in my opinion may be confusing.

    There are two simple ways to differentiate between the user agent string that was taken from HTTP_USER_AGENT and the array of browser names and regex matches:

    • either change userAgent to userAgentString
    • or change userAgents to browsers

    I've chosen the second options and here's the commit.

    Reviewed by quentin389 at 2013-08-04 20:20
  • 5. Error on Mobile_Detect.php line 22

    I'm getting an error: Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in Mobile_Detect.php on line 22 It shows only on my ixwebhosting server. I tested it on hostgator and there is no problem at all. Any idea?

    Reviewed by ezMaverick at 2012-09-27 02:58
  • 6. code style, more tests, test detail, and small other things

    A bunch of commits. Here's a summary.

    1. Added PHPUnit as a composer dependency and committed the composer.lock.
    2. Added getHttpHeader method to get headers by their HTTP name, such as getHttpHeader('User-Agent') or with the PHP flavor, like getHttpHeader('HTTP_USER_AGENT'). Also returns null so it shortens code where you use it and need to test isset($arr['key']) ? $arr['key'] : null.
    3. The constructor now uses dependency injection to more easily test, rather than immediately grabbing stuff from _SERVER when you construct. Backwards compatible. Nothing needs to be passed, in which case it will still use _SERVER if that's what you indended.
    4. Some style stuff, like adding phpdoc comments everywhere, utilizing named constants everywhere, and throwing a BadMethodCallException in __call if the method doesn't start with is. The motivation here is that a typo like isMoblie will return false always, but sometimes that will give you a false positive on a test. Better get an exception.
    5. The file UA_List.inc.php now returns the array so it's easier to use and no need to know what the global variable is called in that file. Similarly, modified the VendorsTest.php to make sure it works.
    6. Added a UserAgentsTest.php which is similar to VendorsTest.php but has a few changes/modifications/improvements:
      • Gives you more detail about your tests. Tells you it ran 500 tests which means that it tested 500 user agents. Also, tells you when tests are incomplete because the UA_List.inc.php file isn't complete with information. Gives you a sense of how complete your tests are.
      • Converts UA_List.inc.php to a JSON file called ualist.json for clarity. I would prefer a JSON format for the test data, if that's ok with you.
      • Caught a potential miss in the VendorsTest.php whereby an array item in the UA_List.inc.php was missing isMobile and isTablet properties. So this new test does some more tests on the data and warns you when there's something missing.
    7. Added more tests to BasicsTest.php. Will keep adding more here as I keep working on this.
    8. Modified setHttpHeaders to be consistent. The method would check for HTTP_ prefix from $this->httpHeaders but wouldn't do that check for when passing as a parameter. I fixed this and updated the tests.
    Reviewed by nicktacular at 2013-07-29 19:45
  • 7. Does not detect Microsoft Surface as a tablet

    Default User Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/6.0; Touch)

    User Agent when in desktop mode: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/6.0; Touch)

    Notice, they are both the same. If you do detect the Microsoft Surface as a tablet, when the user switches their tablet to desktop mode, it will still be recognized as a tablet, when it probably should respect the users decision and recognize it as a desktop.

    Reviewed by bjankord at 2012-12-20 15:21
  • 8. Suggestion: check for updates

    Would be cool to have an api or entry point where we could check the current version, and download a new script into place when it changes. I'd set up a cron job to update my site once a week or so perhaps....

    Thanks to all for sharing.

    Reviewed by HankBrown at 2015-03-07 19:49
  • 9. Performance Speed up

    Small change to save 50% of the time when regex Old: http://www.picfront.org/d/92Uq New: http://www.picfront.org/d/92Ur Only tested with iphone and ipad but do not think that there are problems because

    Reviewed by BitCoding at 2013-11-22 18:26
  • 10. Added Namespace+Autoloading compatibility

    Little piece of PHP to make Mobile_Detect auto-loadable in PSR-0 compatible PHP autoloaders like the Symfony Universal ClassLoader by Fabien Potencier. Since PSR-0 handles an underscore in classnames (on the filesystem) as a slash, "Mobile_Detect.php" autoloaders will try to convert the classname and path to "Mobile\Detect.php". This script will ensure autoloading with:

    • Namespace: Detection
    • Classname: MobileDetect
    • Namespased: \Detection\MobileDetect
    • Autoload path: ./namespaced
    • Converted path: ./namespaced/Detection/MobileDetect.php
    Reviewed by WietseWind at 2013-07-09 04:45
  • 11. isMobile returns true on desktop after Chrome's update

    https://github.com/serbanghita/Mobile-Detect/blob/master/Mobile_Detect.php#L166

    Hi, Chrome just updated last night and the new version is matching one of the LG's phone devices, causing the isMobile to be true on Chrome's desktop.

    http://screencast.com/t/E1R8TAYoqN

    Reviewed by ppartida-LEGACY at 2015-03-04 16:30
  • 12. Completely different website on Mobile Detect

    Hi Guys, it is possible to display a completely different website if detect mobile / tablet? let's say on desktop example.com and on mobile or tablet m.example.com hosted somewhere else even a non wordpress website ... possible?

    Reviewed by umarmughal at 2022-04-27 19:21
  • 13. Update Symfony Mobile Detect Bundle location

    Reviewed by tattali at 2022-04-04 21:27
  • 14. Add Samsung Galaxy Tab S7

    Add support for the Samsung Galaxy Tab S7, this device is currently detected as a mobile instead of a tablet. Not to be confused with the Tab S7+ that was added in 2.8.36.

    Reviewed by maxiengo at 2022-03-25 05:27
  • 15. Generic Fix for new (unknown) Android Tablets (see #846 #872)

    As we can see with #846 and #872 most new Android tablet will be detected as Mobile and not as Tablet. Root cause: "isAndroidOS" will be true and no other regex matches. We can avoid that by checking with negative lookaround "Mobile" and match "Android" for an generic tablet.

    I added new UA string and removed some old one (as they do not longer follow the guideline of browser developer.

    @serbanghita Could you have a look and share your opinion about the generic fix for new Android tablets?

    Could yo commit it to the main project if there are no concerns?

    All tests passed.

    kind regards

    Reviewed by darapa1 at 2022-02-21 18:21
  • 16. Latest iPad versions are not detected as tablets in Safari browser

    Hey!

    The following iPad models are not detected as tablets in the Safari browser. Through the Google Chrome browser, everything is determined as it should:

    iPad Pro 12.9 2020 v14.0 iPad Pro 12.9 2020 v13.4 iPad Pro 12.9 2021 v14.6 iPad 9th v15.1

    Reviewed by Razbash at 2022-02-21 11:30
👮 A PHP desktop/mobile user agent parser with support for Laravel, based on Mobiledetect
👮 A PHP desktop/mobile user agent parser with support for Laravel, based on Mobiledetect

Agent A PHP desktop/mobile user agent parser with support for Laravel, based on Mobile Detect with desktop support and additional functionality. Insta

Jun 30, 2022
A tiny PHP class-based program to analyze an input file and extract all of that words and detect how many times every word is repeated

A tiny PHP class-based program to analyze an input file and extract all of that words and detect how many times every word is repeated

Feb 22, 2022
A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

SqlFormatter A lightweight php class for formatting sql statements. It can automatically indent and add line breaks in addition to syntax highlighting

Jul 2, 2022
A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

SqlFormatter A lightweight php class for formatting sql statements. It can automatically indent and add line breaks in addition to syntax highlighting

Jun 22, 2022
PHP library to detect and manipulate indentation of strings and files

indentation PHP library to detect and manipulate the indentation of files and strings Installation composer require --dev colinodell/indentation Usage

Jun 13, 2022
A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM.

A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM. s('string')->toTitleCase()->ensureRight('y') ==

Jun 19, 2022
A PHP string manipulation library with multibyte support

A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM. s('string')->toTitleCase()->ensureRight('y') ==

Jun 19, 2022
🉑 Portable UTF-8 library - performance optimized (unicode) string functions for php.

?? Portable UTF-8 Description It is written in PHP (PHP 7+) and can work without "mbstring", "iconv" or any other extra encoding php-extension on your

Jun 21, 2022
🔡 Portable ASCII library - performance optimized (ascii) string functions for php.

?? Portable ASCII Description It is written in PHP (PHP 7+) and can work without "mbstring", "iconv" or any other extra encoding php-extension on your

Jun 30, 2022
PHP library to parse urls from string input

Url highlight - PHP library to parse URLs from string input. Works with complex URLs, edge cases and encoded input. Features: Replace URLs in string b

Jun 16, 2022
:accept: Stringy - A PHP string manipulation library with multibyte support, performance optimized

?? Stringy A PHP string manipulation library with multibyte support. Compatible with PHP 7+ 100% compatible with the original "Stringy" library, but t

Jun 21, 2022
Mar 12, 2022
A language detection library for PHP. Detects the language from a given text string.

language-detection Build Status Code Coverage Version Total Downloads Minimum PHP Version License This library can detect the language of a given text

Jun 30, 2022
Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.

cocur/slugify Converts a string into a slug. Developed by Florian Eckerstorfer in Vienna, Europe with the help of many great contributors. Features Re

Jul 1, 2022
Text - Simple 1 Class Text Manipulation Library

Text - Simple 1 Class Text Manipulation Library Do you remember PHP's string functions? If not, just wrap you text with Text! It will save a minute on

Nov 16, 2021
"結巴"中文分詞:做最好的 PHP 中文分詞、中文斷詞組件。 / "Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best PHP Chinese word segmentation module.

jieba-php "結巴"中文分詞:做最好的 PHP 中文分詞、中文斷詞組件,目前翻譯版本為 jieba-0.33 版本,未來再慢慢往上升級,效能也需要再改善,請有興趣的開發者一起加入開發!若想使用 Python 版本請前往 fxsjy/jieba 現在已經可以支援繁體中文!只要將字典切換為 bi

Jun 30, 2022
highlight.php is a server-side syntax highlighter written in PHP that currently supports 185 languages

highlight.php is a server-side syntax highlighter written in PHP that currently supports 185 languages. It's a port of highlight.js by Ivan Sagalaev that makes full use of the language and style definitions of the original JavaScript project.

Jun 25, 2022
A PHP library for generating universally unique identifiers (UUIDs).

ramsey/uuid A PHP library for generating and working with UUIDs. ramsey/uuid is a PHP library for generating and working with universally unique ident

Jul 3, 2022
A sane interface for php's built in preg_* functions
A sane interface for php's built in preg_* functions

Making regex great again Php's built in preg_* functions require some odd patterns like passing variables by reference and treating false or null valu

Jun 20, 2022