Helps detect the user's browser and platform at the PHP level via the user agent

Overview

cbschuld/browser.php

Build Status

Helps detect the user's browser and platform at the PHP level via the user agent

Installation

You can add this library as a local, per-project dependency to your project using Composer:

composer require cbschuld/browser.php

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

composer require --dev cbschuld/browser.php

Typical Usage:

$browser = new Browser();
if( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >=10 ) {
	echo 'You have FireFox version 10 or greater';
}

Browser Detection

This solution identifies the following Browsers and does a best-guess on the version:

  • Opera (Browser::BROWSER_OPERA)
  • WebTV (Browser::BROWSER_WEBTV)
  • NetPositive (Browser::BROWSER_NETPOSITIVE)
  • Edge (Browser::BROWSER_EDGE)
  • Internet Explorer (Browser::BROWSER_IE)
  • Pocket Internet Explorer (Browser::BROWSER_POCKET_IE)
  • Galeon (Browser::BROWSER_GALEON)
  • Konqueror (Browser::BROWSER_KONQUEROR)
  • iCab (Browser::BROWSER_ICAB)
  • OmniWeb (Browser::BROWSER_OMNIWEB)
  • Phoenix (Browser::BROWSER_PHOENIX)
  • Firebird (Browser::BROWSER_FIREBIRD)
  • UCBrowser (Browser::BROWSER_UCBROWSER)
  • Firefox (Browser::BROWSER_FIREFOX)
  • Mozilla (Browser::BROWSER_MOZILLA)
  • Palemoon (Browser::BROWSER_PALEMOON)
  • curl (Browser::BROWSER_CURL)
  • wget (Browser::BROWSER_WGET)
  • Amaya (Browser::BROWSER_AMAYA)
  • Lynx (Browser::BROWSER_LYNX)
  • Safari (Browser::BROWSER_SAFARI)
  • Playstation (Browser::BROWSER_PLAYSTATION)
  • iPhone (Browser::BROWSER_IPHONE)
  • iPod (Browser::BROWSER_IPOD)
  • Google.s Android(Browser::BROWSER_ANDROID)
  • Google.s Chrome(Browser::BROWSER_CHROME)
  • GoogleBot(Browser::BROWSER_GOOGLEBOT)
  • Yahoo!.s Slurp(Browser::BROWSER_SLURP)
  • W3C.s Validator(Browser::BROWSER_W3CVALIDATOR)
  • BlackBerry(Browser::BROWSER_BLACKBERRY)

Operating System Detection

This solution identifies the following Operating Systems:

  • Windows (Browser::PLATFORM_WINDOWS)
  • Windows CE (Browser::PLATFORM_WINDOWS_CE)
  • Apple (Browser::PLATFORM_APPLE)
  • Linux (Browser::PLATFORM_LINUX)
  • Android (Browser::PLATFORM_ANDROID)
  • OS/2 (Browser::PLATFORM_OS2)
  • BeOS (Browser::PLATFORM_BEOS)
  • iPhone (Browser::PLATFORM_IPHONE)
  • iPod (Browser::PLATFORM_IPOD)
  • BlackBerry (Browser::PLATFORM_BLACKBERRY)
  • FreeBSD (Browser::PLATFORM_FREEBSD)
  • OpenBSD (Browser::PLATFORM_OPENBSD)
  • NetBSD (Browser::PLATFORM_NETBSD)
  • SunOS (Browser::PLATFORM_SUNOS)
  • OpenSolaris (Browser::PLATFORM_OPENSOLARIS)
  • iPad (Browser::PLATFORM_IPAD)

History and Legacy

Detecting the user's browser type and version is helpful in web applications that harness some of the newer bleeding edge concepts. With the browser type and version you can notify users about challenges they may experience and suggest they upgrade before using such application. Not a great idea on a large scale public site; but on a private application this type of check can be helpful.

In an active project of mine we have a pretty graphically intensive and visually appealing user interface which leverages a lot of transparent PNG files. Because we all know how great IE6 supports PNG files it was necessary for us to tell our users the lack of power their browser has in a kind way.

Searching for a way to do this at the PHP layer and not at the client layer was more of a challenge than I would have guessed; the only script available was written by Gary White and Gary no longer maintains this script because of reliability. I do agree 100% with Gary about the readability; however, there are realistic reasons to desire the user.s browser and browser version and if your visitor is not echoing a false user agent we can take an educated guess.

I based this solution off of Gary White's original work but have since replaced all of his original code. Either way, thank you to Gary. Sadly, I never was able to get in touch with him regarding this solution.

Testing

The testing with PHPUnit against known user agents available in tests/lists. Each file is tab delimited with the following fields:

User Agent, User Agent Type, Browser, Version, Operating System, Operating System Version

eg

Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16	Browser	Opera	12.16	Linux	Linux	
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1   Browser	Chrome	14.0.835.186	Macintosh	OS X		10_7_2

Tests can be run by phpunit:

vendor/phpunit/phpunit/phpunit
Comments
  • class constructor fix

    class constructor fix

    Class won't properly instantiate on my instance of php5.4+ via public function Browser(). It needs __construct() method instead. This is also backwards compatible.

    opened by davidus-sk 8
  • UC Browser not detecting.

    UC Browser not detecting.

    Its not working for UC Browser. I have made some changes to detect UC Browser too.

    /** * Determine if the browser is UCBrowser or not (last updated 1.7) * @return boolean True if the browser is UCBrowser otherwise false */

    protected function checkBrowserUCBrowser()
    {
        if (stripos($this->_agent, 'UCBrowser') !== false) {
            $resultant = stristr($this->_agent, 'UCBrowser');
            if (preg_match('/\//', $resultant)) {
                $aresult = explode('/', $resultant);
                if (isset($aresult[1])) {
                    $aversion = explode(' ', $aresult[1]);
                    $this->setVersion($aversion[0]);
                }
            } else {
                $aversion = explode(' ', stristr($resultant, 'UCBrowser'));
                if (isset($aversion[1])) {
                    $this->setVersion($aversion[1]);
                }
            }
            if (stripos($this->_agent, 'Mobile') !== false) {
                $this->setMobile(true);
            } else {
                $this->setTablet(true);
            }
            $this->setBrowser(self::BROWSER_UCBROWSER);
            return true;
        }
        return false;
    }
    

    Please, review it and add/modify if necessary.

    opened by anuj9196 5
  • IE 11 don't detected

    IE 11 don't detected

    Hello,

    There is a problem. IE 11 isn't detected. $browser->getBrowser() => Mozilla $browser->getVersion() => 5.0

    There is a new USER-AGENT! My USER-AGENT with IE 11 is: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko

    Can you update?

    Check it: http://msdn.microsoft.com/fr-fr/library/ie/bg182625(v=vs.85).aspx

    Thanks

    opened by ghost 5
  • Add support for Brave browser detection

    Add support for Brave browser detection

    So there is a browser called Brave which is based on the Chromium open-source. Homepage: https://brave.com/

    It's available on pretty much same OSes that Chrome is. They are using a slightly changed User-Agent on Windows though (haven't checked linux one yet).

    Windows 10 x64: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Brave Chrome/74.0.3729.157 Safari/537.36

    Looks like on android they are using same User-Agent as the mobile Chrome.

    Android 9: Mozilla/5.0 (Linux; Android 9; *device*) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.136 Mobile Safari/537.36

    I think Browser.php should add support for Brave Chrome keyword in case they change their mobile User-Agent to match the Window's scheme so it's possible to disguise mobile Chrome from Brave.

    opened by Zaczero 4
  • Support newer Edge versions

    Support newer Edge versions

    In newer versions of Edge (based on Chrome) the user agent is using the "Edg" code name instead of "Edge".

    Example user agent of Edge Version 81.0.416.41 (Official Build) beta (64 bit) Downloaded from https://www.microsoftedgeinsider.com/

    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.83 Safari/537.36 Edg/81.0.416.41
    

    Related issues #89

    opened by GramThanos 3
  • Edge is erroneously being detected as a Chrome

    Edge is erroneously being detected as a Chrome

    Hi, Edge is erroneously being detected as a Chrome (Browser::BROWSER_EDGE) .

    Edge on Mac reports: Chrome Edge on Windows reports: Chrome Edge on Linux reports: Chrome

    Edge v.79.0.309.71

    Any help would be appreciated to show correct browser name.

    opened by angelscabrerag 3
  • License conflict

    License conflict

    Hi At the root of the project it is indicated that the program is licenced under the MIT, but in Browser.php it still mentions the General Public License.

    Can that be updated? Mario

    opened by mdeweerd 3
  • Identify PlayStation systems

    Identify PlayStation systems

    The PlayStation 3, 4 and Vita web browser share a pretty simple structure:

    Mozilla/5.0 (Playstation $version[;] $firmware) AppleWebkit(......)
    

    $version: 3, 4, Vita $firmware: X.XX (i.e. 3.55)

    The PlayStation 3 has a semi-colon, appearently, whilst Vita and 4 do not.

    To classify:

        const BROWSER_PLAYSTATION = "PlayStation";
        const PLATFORM_PLAYSTATION = "Sony PlayStation";
    

    PS 3 and 4 are "Desktop" and not mobile. Vita is mobile.

    Unfortunately I am not perfectly sure of the results for the PSP.

    Could they be implemented?

    opened by IngwiePhoenix 3
  • some gaps

    some gaps

    iPhone unknown Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) CriOS/28.0.1500.16 Mobile/10B350 Safari/8536.25

    Safari unknown Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) DumpRenderTree/0.0.0.0 Safari/536.11

    iPhone 28.0 Mozilla/5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) CriOS/28.0.1500.16 Mobile/10B142 Safari/8536.25

    Internet Explorer 9.0 Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Radar; Orange) ("Mobile")

    opened by Yaffle 3
  • Composer best practices

    Composer best practices

    Hello,

    it would be nice to remove the version property of composer.json file and use git tag to release versions.

    This way is the simplest way of providing stable version as long as a developement one.

    opened by romainneutron 3
  • Suggestion: Getter/Setter made nicer

    Suggestion: Getter/Setter made nicer

    Hey there! When I work with getters and setters, I really like using magic methods since they make things easyer. Here is what i'd recommend for this very, VERY awesome class!

    <?php class Browser {
    
        // ......all the other code
    
    
        /*
         * This function will call a getter function to get the information.
         * Example: $Browser->browser;
         * This will actually call $browser->getBrowser(); - it just looks a little more natural.
         * @return mixed
        */  
        public function __get($what) {
            $method = "get".ucfirst($what);
            if(method_exists($this, $method))
                return call_user_func(array($this, $method));
            else
                return $this->$what;
        }
    
        /*
         * The same as above, just for functions like setUserAgent.
         * @return void
        */
        public function __set($name, $value) {
            $method = "set".ucfirst($name);
            if(method_exists($this, $method))
                return call_user_func(array($this, $method), $value);
            else
                return $this->$name;
        }
    
        // ......all the other code
    
    }
    

    Just a thought =)

    opened by IngwiePhoenix 3
  • Edge showing Chrome

    Edge showing Chrome

    The getBrowser() method is showing 'Chrome' in browser Microsoft Edge (Version 104.0.1293.70)

    The class is checking for Edge/ but Edge changed it to: Edg/

    opened by RonJeremyR6 2
  • speed

    speed

    I think that checking the user agent 50+ times is incorrect, you can speed up the script several times by disassembling the user agent, and then checking each parameter according to the conditions.

    opened by BuslikDrev 1
  • Retrieved version number and PHP 8

    Retrieved version number and PHP 8

    The getVersion method is documented to return only a single period:

        /**
         * The version of the browser.
         * @return string Version of the browser (will only contain alpha-numeric characters and a period)
         */
        public function getVersion()
        {
            return $this->_version;
        }
    

    However, it may contain multiple. E.g. '15.1.4'.

    This was not really an obvious issue, until PHP 8, which changes how automatic casting works...

    php -r 'var_dump("15.1.4" == 15.1);' bool(false)

    It returns false as it now does a string comparison rather than an automatic cast, if it doesn't fully match the pattern of a float (I think!!). I was relying on this, as I'm sure other users were.

    This change to the setVersion method fixes it by making it only have one period section:

        /**
         * Set the version of the browser
         * @param string $version The version of the Browser
         */
        public function setVersion($version)
        {
            $this->_version = preg_replace('#^([^\.]*\.[^\.]*)\..*#', '$1', preg_replace('/[^0-9,.,a-z,A-Z-]/', '', $version));
        }
    

    This provides us a return value that continues to work...

    $ php -r 'var_dump("15.1" == 15.1);'
    bool(true)
    
    opened by chrisgraham 2
  • Consider using the PSR-4 autoloader

    Consider using the PSR-4 autoloader

    As title, it seems that this class still uses the classmap approach to load the Browser class in composer.json.

    I think we can consider using the PSR-4 autoloader and the advantages are as follows:

    • The PSR-4 approach will have the namespace and it can avoid the class name collision.

    Once this issue is accepted, I can help this issue :).

    opened by peter279k 2
  • Wrong isTablet result for opera on Android 6 Tablet

    Wrong isTablet result for opera on Android 6 Tablet

    UserAgent is "Mozilla/5.0 (Linux; Android 6.0.1; SM-T580 Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Safari/537.36 OPR/43.0.2246.121183"

    Result for $browser->isTablet() is false

    opened by diasflack 0
Releases(v1.9.6)
  • v1.9.6(Apr 14, 2020)

    Adds

    • support for Android Edge

    Removes

    • tests for 7.2 as it was dropped by Travis CI/trusty

    Changes

    • moved from /lib to /src for classes to get ready for 2.0 which will support PSR-4 loading
    Source code(tar.gz)
    Source code(zip)
  • 1.9.5(Apr 6, 2020)

    Added

    • better support for the Edge Browser
    • updated travis to trusty and removed 7.2, added 7.4 for tests
    • added better/additional Edge tests

    Thanks

    • thank you to @GramThanos for the PRs
    Source code(tar.gz)
    Source code(zip)
  • 1.9.4(Jul 9, 2019)

    Added

    • Added better support for Firefox Mobile
    • Added support for the Brave browser
    • Added support for the UCBrowser
    • Added more tests for specific User Agents and more IE tests (removed duplicate UAs as well)
    Source code(tar.gz)
    Source code(zip)
  • 1.9.1(Jul 9, 2019)

    6/19/2019: Update (Version 1.9.1)

    • Added Firefox iOS (gejobj)
    • Corrected 'Vivalidi' to 'Vivaldi' (adaxi)
    • Reset enhancement (yahasana)
    • Enforce using precise distribution until End Of Life for Travis CI (bburnichon)
    • Lazy load browser class on demand (bburnichon)
    Source code(tar.gz)
    Source code(zip)
  • 1.9.3(Jul 8, 2019)

  • 1.9.2(Jun 26, 2019)

    Added testing to this release, updated the firefox and chrome sensors. Test suite addresses Firefox, Chrome and Opera detection with 3684 individual user-agent tests.

    Added

    • PHPUnit Tests for Firefox, Opera and Chrome (3684 tests, 7368 assertions)
    • Stronger tests for Firefox and Chrome

    Removed

    • Dropped support for 5.x PHP due to updates to PHPUnit and legacy nature of 5.X
    Source code(tar.gz)
    Source code(zip)
Owner
Chris Schuld
SaaS entrepreneur, full-stack engineer, currently obsessed with Jamstack: React in the front, serverless in the back.
Chris Schuld
PHP class for parsing user agent strings (HTTP_USER_AGENT).

PHP class for parsing user agent strings (HTTP_USER_AGENT). Includes mobile checks, bots and banned bots checks, browser types/versions and more. Based on browscap (via phpbrowscap), Mobile_Detect and ua-parser. Created for high traffic websites and fast batch processing.

Mikolaj Misiurewicz 44 Jul 26, 2022
uaDetect – A multi-language port of Browserscope's user agent parser

uaDetect is a lightweight for detecting mobile devices. It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.

Fadjrir Herlambang 1 Jan 7, 2022
Remote or monitor your PocketMine:MP server via browser.

PMRemote Remote or monitor your server via browser. Features Monitor (TPS, Server load, Players count) TODO: Remote (Access server console like RCON,

null 11 Dec 7, 2022
Small class to extract + compress .zip, .gz, .rar archives via browser.

The Unzipper The Unzipper extracts .zip and .rar archives or .gz/tar.gz files on webservers. It detects .zip/.rar/.tar.gz/.gz archives and let you cho

Lục Thiên Phong 10 Dec 24, 2022
Moodle plugin to limit the access to course content according to the user level in Block Game.

Moodle plugin to limit the access to course content according to the user level in Block Game.

null 4 Oct 18, 2022
Elastic APM PHP Agent

Elastic APM Agent for PHP This is the official PHP agent for Elastic APM. The PHP agent enables you to trace the execution of operations in your appli

elastic 217 Dec 13, 2022
salah eddine bendyab 18 Aug 17, 2021
Tars is a high-performance RPC framework based on name service and Tars protocol, also integrated administration platform, and implemented hosting-service via flexible schedule.

TARS - A Linux Foundation Project TARS Foundation Official Website TARS Project Official Website WeChat Group: TARS01 WeChat Offical Account: TarsClou

THE TARS FOUNDATION PROJECTS 9.6k Jan 1, 2023
Silverstripe-masquerade - SilverStripe module to allow users to "masquerade" as other users

SilverStripe Masquerade Module About This module is designed to allow an Administrator to "login" as another "Member" without changing their password

Daniel Hensby 14 Apr 14, 2022
Library for PHP 7.4+ to detect Browsers and Devices

This library requires PHP 7.4+. Also a PSR-3 compatible logger and a PSR-16 compatible cache are required. In

Thomas Müller 37 Oct 2, 2022
Rules to detect game engines and other technologies based on Steam depot file lists

SteamDB File Detection Rule Sets This is a set of scripts that are used by SteamDB to make educated guesses about the engine(s) & technology used to b

Steam Database 103 Dec 14, 2022
Library allows to detect emoji, remove emoji, encode emoji and decode emoji in string.

It allows to detect emoji, remove emoji, encode emoji and decode emoji in string. Installation composer require anisimov/emoji How to use Encode and

Aleksey Anisimov 9 Nov 8, 2022
Mobile detect change theme and redirect based on device type. Magento 2 module.

Magento 2 Mobile Detect Theme Change Magento 2 Mobile detect system can be used to load different themes base on the client device (desktop, tablet, m

EAdesign 27 Jul 5, 2022
HLedger is cross-platform accounting software for both power users and folks new to accounting

HLedger Plain Text Accounting on Nextcloud HLedger is cross-platform accounting software for both power users and folks new to accounting. It's good f

Ryan Boder 11 Jan 20, 2022
QuestionApp - a platform where users can ask questions and discuss about the subject they are curious about

QuestionApp About The Project It can be a trend according to the number of likes and comments that members can ask questions. ![Alt Text] Ask your any

Tolga Bayrak 4 Oct 7, 2022
Detect flaws in your architecture, before they drag you down into the depths of dependency hell ...

Detect flaws in your architecture before they drag you down into the depths of dependency hell ... What it does System Requirements Installation Phive

Michael Haeuslmann 507 Dec 27, 2022
Tool to detect assumptions

PHP Assumptions Setup $ composer require --dev rskuipers/php-assumptions Introduction PHP Assumptions is the result of a proof of concept inspired by

Rick Kuipers 153 Dec 8, 2022
The main scope of this extension is to help phpstan to detect the type of object after the Assert\Assertion validation.

PHPStan beberlei/assert extension PHPStan beberlei/assert Description The main scope of this extension is to help phpstan to detect the type of object

PHPStan 33 Jan 2, 2023
Banana detect adblock :Detects ad blockers (AdBlock, ublock, ...)

banana detect adblock :Detects ad blockers (AdBlock, ublock, ...)

banana 24 Dec 28, 2022