Reputation: 6080
I found some php code for detecting if a user is on Chrome:
<?php
$b_name = get_browser_name($_SERVER['HTTP_USER_AGENT']);
function get_browser_name($user_agent){
if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
elseif (strpos($user_agent, 'Edge')) return 'Edge';
elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
elseif (strpos($user_agent, 'Safari')) return 'Safari';
elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
return 'Other';
}
echo "You browser is <b>$b_name</b> .";
?>
It seems to work when I test it, but when deployed it seems to be giving off a lot of false negatives where the user is on Chrome but it shows Mozilla.
Any idea where it might be going wrong? Or is this good code?
Upvotes: 1
Views: 7173
Reputation: 659
To be almost hundred percent sure of what you are getting as the browser, use the The Wolfcast BrowserDetection PHP class. With this class at your hands, it will be pretty easy to get both the browser and the platform, whether its on cellphone, desktop, linux or a MAC computer.
It detects browsers such as Chrome, Edge, Firebird, Firefox, Internet Explorer, Internet Explorer Mobile, Opera, Opera Mini, Opera Mobile, Android, BlackBerry, BlackBerry Tablet OS, GNU IceCat, GNU IceWeasel, iCab, Konqueror, Lynx, Mozilla, MSN TV, Netscape, Nokia Browser, Phoenix, Safari, Samsung Internet, UC Browser.
$browser = new Wolfcast\BrowserDetection();
if ($browser->getName() == Wolfcast\BrowserDetection::BROWSER_FIREFOX &&
$browser->compareVersions($browser->getVersion(), '5.0') >= 0) {
echo 'You are using FireFox version 5 or greater.';
}
Upvotes: 0
Reputation: 2767
If you are in hurry & a very-fast-responding system is not a serious requirement for now, you can use: get_browser & then parse it with strpos()
or using regexp
.
In order to get accurate results with get_browser
, make sure you take care of following recommendation:
Note: In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system. browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here. While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.
But if you are looking for a more reliable solution, AS STATED HERE its better to use one of the packages in this repository :https://github.com/ThaDafinser/UserAgentParser
You can test its speed, large-enough list of OS/Browsers & accuracy Here.
Upvotes: 1
Reputation: 8278
why not using the internal php function get_browser ??
get_browser — Tells what the user's browser is capable of
example from the manual
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
print_r($browser);
Upvotes: 2