How to detect "Google Chrome" as the user-agent using PHP?
Asked Answered
C

4

22

I'm interested to know whether the user-agent is "Chrome" at the server end using PHP. Is there a reliable regular expression for parsing out the user-agent string from the request header?

Cindicindie answered 15/6, 2010 at 18:20 Comment(0)
T
31

At this point, too many browsers are pretending to be Chrome in order to ride on its popularity as well as combating abuse of browser detection for a simple match for "Chrome" to be effective anymore. I would recommend feature detection going forward, but Chrome (and WebKit/Blink in general) is notorious for lying to feature detection mechanisms as well, so even that isn't as great as it's cracked up to be anymore either.

I can only recommend staying on top of things by comparing its known UA strings with those of other browsers through third-party sites, and creating patterns from there. How you do this depends entirely on the strings themselves. Just keep in mind that due to the nature of browsers, and UA strings, there can never be a "reliable" regular expression for matching them.

In PHP, the relevant server var is $_SERVER['HTTP_USER_AGENT'].

Tarr answered 15/6, 2010 at 18:23 Comment(7)
Nice one. Using preg_match for detecting Chrome would surely be an overhead.Sidestep
Why do you need the !== false ? wouldn't be easier just if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome')) ?Clean
@Tuga: If the string starts with 'Chrome', strpos() returns 0. Since 0 == false, the if code won't run, but you want it to. The function returns an actual false if the string isn't found, so you have to compare it by type using !== false. This is also why your answer is wrong.Tarr
I disagree: This if clause will evaluate to true on the versions of the following browsers: Chrome, Maxthon, Flock, IE 10.0, IE 9.0, IE 8.0, Iron, RockMelt. More Info at: useragentstring.com/pages/Browserlist !!!Donalddonaldson
@NaNsTtiX you are somewhat right. But: 1) Maxthon, Flock, Iron and RockMelt are based on Chrome (so they basically ARE Chrome); 2) IE has "chrome" in its useragent ONLY if there is Chrome Frame installed (so IE becomes Chrome in some way). If somebody needs to detect IE separately, they could add stripos($_SERVER['HTTP_USER_AGENT'], 'chromeframe') === false condition.Dentistry
Opera has the word "Chrome" on it's user agent too, you can filter Opera browsers excluding ua containing "OPR"Islander
Microsoft Edge also has Chrome in its UA string, to weed that out, check out "Edge" as wellLumber
H
20

Worth mentioning that if you also want to include Chrome for iOS, you will need to match against "CriOS" as well:

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false
 || strpos($_SERVER['HTTP_USER_AGENT'], 'CriOS') !== false) {
    // User agent is Google Chrome
}
Haggar answered 3/6, 2013 at 10:13 Comment(1)
hey Adam I have a question for you becuase I should put in my code the second line? what is its works in my code? becuase when I remove this line from my code and try run it , it does not workTacmahack
P
9

Building on @Adams answer, more accurately detecting Google Chrome by exclude some browsers with "Chrome" in the user agent string using useragentstring.com and udger.com :

if(preg_match('/(Chrome|CriOS)\//i',$_SERVER['HTTP_USER_AGENT'])
 && !preg_match('/(Aviator|ChromePlus|coc_|Dragon|Edge|Flock|Iron|Kinza|Maxthon|MxNitro|Nichrome|OPR|Perk|Rockmelt|Seznam|Sleipnir|Spark|UBrowser|Vivaldi|WebExplorer|YaBrowser)/i',$_SERVER['HTTP_USER_AGENT'])){
    // Browser might be Google Chrome
}
Pinder answered 15/11, 2015 at 12:37 Comment(0)
B
1

There are actually ways to detect browser. But, as one of the answers states, browsers, indexing bots extensively mimic their real name, so, once successful manual function may stop working well any time.

Browser detection sometimes needed if you are printing something with specific browser where CSS media rules are poorly implemented in cross-browser compatibility by the day of my answer.

Simple unreliable way

Just to grab specific browser by UA string, you may use function like that (a modified fork from here):

function get_browser_manually() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $browser = "n/a";
    $browsers = array(
        '/msie/i' => 'Internet explorer',
        '/IE/i' => 'Internet explorer',
        '/Edg/i' => 'Edge',
        '/gecko/i' => 'Firefox',
        '/fox/i' => 'Firefox',
        '/safari/i' => 'Safari',
        '/opera/i' => 'Opera',
        '/mobile/i' => 'Mobile browser',
        '/phone/i' => 'Mobile browser',
        '/Yowser/i' => 'Yandex Browser',
        '/Ya/i' => 'Yandex Browser',
        '/Presto/i' => 'Opera',
        '/Chrome/i' => 'Chrome'
    );

    foreach ($browsers as $regex => $value) {
    if (preg_match($regex, $user_agent)) { 
        $browser = $value; 
        return $browser;
    }
    }
}

echo "Browser: " . get_browser_manually();

Built in & reliable way

PHP has built in get_browser() function to get browser and platform. Prior to PHP7 it was slow, but, now it reportedly became much quicker.

In order to make this thing working you need to download extra file (small, medium, large depending onto your detection accuracy needs) from browscap.org, copy file in PHP directory and include it in php.ini:

[browscap]
; http://php.net/browscap
browscap = C:\PHP\extras\lite_php_browscap.ini

In PHP script then you can call get_browser() and use output:

$browser = get_browser(null, true);
echo '<pre>';
echo print_r($browser,1);
echo '</pre>';

The output for Chrome would be something like this:

Array
(
    [browser_name_regex] => ~^mozilla/5\.0 \(.*windows nt 10\.0.*\) applewebkit ... ...
    [browser_name_pattern] => Mozilla/5.0 (*Windows NT 10.0*) applewebkit... ...
    [parent] => Chrome 89.0
    [platform] => Win10
    [comment] => Chrome 89.0
    [browser] => Chrome
    [version] => 89.0
    [device_type] => Desktop
    [ismobiledevice] => 
    [istablet] => 
)

If you need testing other browsers, consider lightweight Useragent switcher extension for Chrome:

Note: browsecap file is not default configuration, and disabled by default. Make sure you call get_browser() safely by checking if it is available to be called:

if (!ini_get('browscap')) {

    // Not set, use other custom func to detect browser:
    $browser = get_browser_manually();
} else {

    // Browsecap.ini was set, use it:
    $browser = get_browser(null, true);
}
Bobstay answered 5/9, 2021 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.