Detect on which browser current web application is running - php

I wanted to know in PHP, how to detect on which browser my web application is running.
e.g.
If current browser is chrome then alert("Chrome browser processing") otherwise alert("rest browser processing");
echo $_SERVER['HTTP_USER_AGENT'];
Below output I am getting If i execute above code :
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.21 Safari/532.0
Please suggest your pointers to detect exact browser name.
Thanks,
-Pravin

This has some useful code.
Basically, in your case, you can just look for the string "Chrome". In general, it might take a bit more logic, since, for example, the string "Safari" is found in the user-agents provided by other browsers than Safari (including Chrome). PHP provides the 'browser' element for this.

Personally, I'd use Javascript for this one.
if(navigator.userAgent.match(/Chrome/i)) {
alert("You're using Chrome!");
}
else {
alert("You're using something other than Chrome!");
}
... but if you really wanted to, you could accomplish the same thing in PHP:
if (preg_match("/Chrome/i", $_SERVER['HTTP_USER_AGENT']) == 0) {
// zero matches
echo "<script>alert('You're not using Chrome!')</script>";
} else {
echo "<script>alert('You're using Chrome!')</script>";
}

Related

Codeigniter User Agent detect Opera browser as Chrome

I'm trying to show the browser that I used to open my site using Codeigniter User Agent Libraries. When I open with IE,Chrome,Firefox,and Safari, User agent return the right value. But when I open with Opera, it return "Chrome" value.
here is part of my code:
Controller
*** another code ***
$this->load->library('user_agent');
$data['browser'] = $this->agent->browser();
$this->load->view('agent',$data);
*** another code ***
View
Your browser is <span><?php echo $browser; ?></span>.
the result if I open with opera is this:
Your browser is Chrome.
My question is, why it return Chrome? How can I fix this problem?
Thanks.
It looks like the user agent string in opera (since version 15) is this:
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36 OPR/15.0.1147.100
You might need to extend the user_agent library to do a check to see if the user agent string contains OPR.
https://dev.opera.com/blog/opera-user-agent-strings-opera-15-and-beyond/

PHP Unable to determine user's browser information

I want to determine which user uses which browser when they visit to my website.
For this process i'am using $_SERVER['HTTP_USER_AGENT'] but when i try to print it while i'am using chrome i get this result(on localhost):
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
What can i do to fix that ? Any help would be appriciated
$_SERVER['HTTP_USER_AGENT']
This gives the information of the browser as you said.
Always keep in mind that HTTP_USER_AGENT can be easily spoofed by the user.
get_browser() gives the browser's capability.
you can also use the php class provided by Wolfcast
use like:
$browser = new BrowserDetection();
echo 'You are using ', $browser->getBrowser(), ' version ', $browser->getVersion();
if you really want to differentiate the browsers from the client-side you could use the javascript to find the browser and apply the changes through that based on different browser.
this is a code that i obtained from internet that exactly differentiate the browsers.
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
if(isFirefox){
//do the change
} else if (isChrome){
//do the change
}

PHP: Browser version number user-agent with Version/x.x.x (Safari & Opera)

I wrote a simple class to check for user agents to display a warning for incompatible browsers. I'm doing this server side, I know it's possible client side.
Okey first off, I'm not much good for writing regexes..
I wrote a regex that searches for lower case browser names followed by the version number.
I do a foreach() with an array something like this:
<?php
$browsers = Array('msie','chrome','safari','firefox','opera');
foreach($browsers as $i => $browser)
{
$regex = "#({$browser})[/ ]([0-9.]*)#i";
if(preg_match($regex, $useragent, $matches))
{
echo "Browser: \"{$matches[0]}\", version: \"{$matches[1]}\"";
}
}
?>
This would yield: Browser: "Firefox", version "23.0.6".
I found this works for Firefox, MS IE, and older versions of Opera. However some browsers like Safari and the newer versions of Opera have a different user-agent string that contains Version/x.x.x, which is
Just to give you the an idea here are 3 user-agent strings and what I need is highlighted.
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14
So in each of these the following human logic correct:
If there is a Version/x.x.x in the string that is the version number.
If there isn't then Browsername/x.x.x is the version number.
Also if you look at the 1st and last user-agent string above, you can see the Version can come before or after the browser name.
Can somebody help me to make a regex to be used with preg_match()? Do I need to use a conditional statement or can I search for optional groupings? I'm a bit confused..
Thanks!
Edit 17-09-2013: I forgot to mention, I don't want to use get_browser(), it uses a huge library to detect the browsers capabilities etc. I only need a short "whitelist" of browsers that should take a few milliseconds rather than a few hundred ms to read the browse cap.ini files.. Otherwise George's answer would've been the answer..
Ended up doing it a little differently since I had some trouble with some browsers with Remus' answer.
<?php
function get_useragent_info($ua)
{
$ua = is_null($ua) ? $_SERVER['HTTP_USER_AGENT'] : $ua;
// Enumerate all common platforms, this is usually placed in braces (order is important! First come first serve..)
$platforms = "Windows|iPad|iPhone|Macintosh|Android|BlackBerry";
// All browsers except MSIE/Trident and..
// NOT for browsers that use this syntax: Version/0.xx Browsername
$browsers = "Firefox|Chrome";
// Specifically for browsers that use this syntax: Version/0.xx Browername
$browsers_v = "Safari|Mobile"; // Mobile is mentioned in Android and BlackBerry UA's
// Fill in your most common engines..
$engines = "Gecko|Trident|Webkit|Presto";
// Regex the crap out of the user agent, making multiple selections and..
$regex_pat = "/((Mozilla)\/[\d\.]+|(Opera)\/[\d\.]+)\s\(.*?((MSIE)\s([\d\.]+).*?(Windows)|({$platforms})).*?\s.*?({$engines})[\/\s]+[\d\.]+(\;\srv\:([\d\.]+)|.*?).*?(Version[\/\s]([\d\.]+)(.*?({$browsers_v})|$)|(({$browsers})[\/\s]+([\d\.]+))|$).*/i";
// .. placing them in this order, delimited by |
$replace_pat = '$7$8|$2$3|$9|${17}${15}$5$3|${18}${13}$6${11}';
// Run the preg_replace .. and explode on |
$ua_array = explode("|",preg_replace($regex_pat, $replace_pat, $ua, PREG_PATTERN_ORDER));
if (count($ua_array)>1)
{
$return['platform'] = $ua_array[0]; // Windows / iPad / MacOS / BlackBerry
$return['type'] = $ua_array[1]; // Mozilla / Opera etc.
$return['renderer'] = $ua_array[2]; // WebKit / Presto / Trident / Gecko etc.
$return['browser'] = $ua_array[3]; // Chrome / Safari / MSIE / Firefox
/*
Not necessary but this will filter out Chromes ridiculously long version
numbers 31.0.1234.122 becomes 31.0, while a "normal" 3 digit version number
like 10.2.1 would stay 10.2.1, 11.0 stays 11.0. Non-match stays what it is.
*/
if (preg_match("/^[\d]+\.[\d]+(?:\.[\d]{0,2}$)?/",$ua_array[4],$matches))
{
$return['version'] = $matches[0];
}
else
{
$return['version'] = $ua_array[4];
}
}
else
{
/*
Unknown browser..
This could be a deal breaker for you but I use this to actually keep old
browsers out of my application, users are told to download a compatible
browser (99% of modern browsers are compatible. You can also ignore my error
but then there is no guarantee that the application will work and thus
no need to report debugging data.
*/
return false;
}
// Replace some browsernames e.g. MSIE -> Internet Explorer
switch(strtolower($return['browser']))
{
case "msie":
case "trident":
$return['browser'] = "Internet Explorer";
break;
case "": // IE 11 is a steamy turd (thanks Microsoft...)
if (strtolower($return['renderer']) == "trident")
{
$return['browser'] = "Internet Explorer";
}
break;
}
switch(strtolower($return['platform']))
{
case "android": // These browsers claim to be Safari but are BB Mobile
case "blackberry": // and Android Mobile
if ($return['browser'] =="Safari" || $return['browser'] == "Mobile" || $return['browser'] == "")
{
$return['browser'] = "{$return['platform']} mobile";
}
break;
}
return $return;
} // End of Function
?>
Given your handful of results, this works. It may not in all cases, but it's going to reduce your processing time drastically.
I'd use a single regular expression to extract the version:
(?:version\/|(?:msie|chrome|safari|firefox|opera) )([\d.]+)
And then, since you're only searching for a handful of exact strings, you can use php's stripos() to check for the browser string.
<?php
$useragent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1";
$browsers = Array('msie','chrome','safari','firefox','opera');
preg_match("/(?:version\/|(?:msie|chrome|safari|firefox|opera) )([\d.]+)/i", $useragent, $matches);
$version = $matches[1];
$browser = "";
foreach($browsers as $b)
{
if (stripos($useragent, $b) !== false)
{
$browser = ucfirst($b);
break;
}
}
echo "$browser: $version";
?>
The benefits of doing it this way are immediate:
You don't need to test the useragent multiple times with the regular expression.
stripos() is significantly faster at processing than regular expressions.
You can also play around with the regex here: http://regex101.com/r/lE6lI2
Have you heard of browscap and get_browser()? On my install:
$info = get_browser();
echo $info->browser; // Chrome
echo $info->version; // 29.0
To use it, grab yourself a copy of a PHP version of browscap.ini from here (e.g. php_browscap.ini), reference it in php.ini under the browscap directive, and you're good to go.
This class / function does a nice job:
old dead link: https://github.com/diversen/coscms/blob/master/coslib/useragent.php
I have tested this with an iphone and opera. At the same time you will get the OS the browser is running on .)
Edit:
I can see that this function has got a git repo of it's own. Use this as this is updated and maintained:
https://github.com/donatj/PhpUserAgent

Reliable way to detect Chrome on Mac in PHP?

As the title says, is there a reliable way to detect whether a user is visiting my page using Chrome on Mac using PHP?
I have a bug that only displays when using Chrome on Mac, and until I get it sorted out I would like to have a popup to recommend the users to use a different browser.
Use $_SERVER['HTTP_USER_AGENT'] to find the users' user agent and a function to check if this is within the string.
//The following will find out whether the user is using a Mac, obviously you can change this by echoing the user agent to find out what you need to search for.
$browser = strpos($_SERVER['HTTP_USER_AGENT'], "Chrome");
$os = strpos($_SERVER['HTTP_USER_AGENT'], "Macintosh; Intel Mac OS X");
if($browser !== false && $os !== false) {
//do stuff if on a mac with Chrome
}
This will work with any type of Mac OS X software and any version of Chrome. If you want to narrow your results down further, you can just use:
if($_SERVER['HTTP_USER_AGENT'] == "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11" ) {
//do stuff here
}
It would be better if you posted the code you're having issues with rather than creating a hacky fix.
However, you can use $_SERVER['HTTP_USER_AGENT'] to check the users browser/OS.
To aid, you would expect something like Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11 from a Mac user on Chrome.
Note
The user agent isn't always set so use isset first to avoid notices appearing.
I know you're looking for the PHP solution to find the browser, but since the problems you are most likely to encounter with a specific browser are client-side, there should be no need to detect it from the server-side.
So here's a solution with javascript, and if you get the match you expect, you can hide the body, or display a popup, or send it to your server, set a cookie, or whatever you see appropriate to "fix" your problem (although you should be looking into really fixing the problem...)
Look here for the source:
function that_is_called_on_load() {
if (BrowserDetect.browser == "Chrome" && BrowserDetect.OS == "Mac") {
alert("You are using mac, sorry.");
window.location = "mac_chrome.php";
}
}
This is a very "dirty" solution, and it might be slightly more accurate/reliable than the server-side one.

browser name in php?

How can we get Browser Name and Version information using php script?
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>
As Palantir says, additionally have a look at the get_browser function, where you can check also capabilities enabled in the browser.
http://php.net/manual/en/function.get-browser.php
You will need to create function to translate user agent data into common names of browsers
For example, $_SERVER['HTTP_USER_AGENT'] could return
Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9* is firefox
or
Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.55 Safari/533.4 is Chrome
The details provide you with the rendering engine, code base, version, os, etc...
I'd suggest using preg_match and/or a list of known browsers is you want to do something like
echo browserCommonName($_SERVER['HTTP_USER_AGENT']);
to output "Google Chrome".
browserCommonName($userAgent) would need a list of known browsers.
edit: just noticed get_browser buit into php does this, my bad for not reading the thread.
See get_browser().
<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
print_r($browser);
?>
All in all, you can't. You can certainly try to get it, and you're almost certainly guaranteed to get something that looks like what you want; but there is absolutely no way of checking wether or not the information is correct. When you receive a user agent string, the browser on the other end could be truthful, or it could be lying. When dealing with users, always assume that it is, in fact, lying.
There is no "best way" to deal with this, but what you most likely want to do is test your site with a wide variety of browsers, use portable HTML and CSS techniques, and if you absolutely must, fill the holes with JavaScript.
Choosing what data to send to a browser based on what browser you think it is, is a Bad Idea™.
You could always take a look at the php function get_browser http://php.net/manual/en/function.get-browser.php. You will need $_SERVER['HTTP_USER_AGENT'] for this.
You may also want to take a look at Chris Schuld Browser Detection Class. http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php.html

Categories