How can I detect the browser with PHP or JavaScript?
How can I detect if the user is not using any of the browsers Chrome, Firefox or Internet Explorer using JavaScript or PHP?
I might point out that knowing the browser is only useful as long as the agent-string hasn’t been modified. I’m guessing you already know this tho.
12 Answers 12
The best way to do this in JS I found is on Quirksmode. I made one for PHP which should work with common browsers :
$browser = array( 'version' => '0.0.0', 'majorver' => 0, 'minorver' => 0, 'build' => 0, 'name' => 'unknown', 'useragent' => '' ); $browsers = array( 'firefox', 'msie', 'opera', 'chrome', 'safari', 'mozilla', 'seamonkey', 'konqueror', 'netscape', 'gecko', 'navigator', 'mosaic', 'lynx', 'amaya', 'omniweb', 'avant', 'camino', 'flock', 'aol' ); if (isset($_SERVER['HTTP_USER_AGENT'])) < $browser['useragent'] = $_SERVER['HTTP_USER_AGENT']; $user_agent = strtolower($browser['useragent']); foreach($browsers as $_browser) < if (preg_match("/($_browser)[\/ ]?([0-9.]*)/", $user_agent, $match)) < $browser['name'] = $match[1]; $browser['version'] = $match[2]; @list($browser['majorver'], $browser['minorver'], $browser['build']) = explode('.', $browser['version']); break; >> >
so i read around and this is what i found. whether its php or javascript, they both get the information that what browser it is through httpheaders, also the way Apache does. Correct if i am wrong.
Here is JavaScript code through which you can easily detect the browser.
var userAgent = navigator.userAgent.toLowerCase(); // Figure out what browser is being used. var Browser = < Version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1], Chrome: /chrome/.test(userAgent), Safari: /webkit/.test(userAgent), Opera: /opera/.test(userAgent), IE: /msie/.test(userAgent) && !/opera/.test(userAgent), Mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent), Check: function() < alert(userAgent); >>; if (Browser.Chrome || Browser.Mozilla) < // Do your stuff for Firefox and Chrome. >else if (Browser.IE) < // Do something related to Internet Explorer. >else < // The browser is Safari, Opera or some other. >
There is actually a function in PHP for that, get_browser.
True. Here is a pure php version of this function. It auto-updates the browsecap file too. code.google.com/p/phpbrowscap
PHP code from get_browser() is totally working for me 😉
elseif (preg_match('/macintosh|mac os x/i', $u_agent)) < $platform = 'mac'; >elseif (preg_match('/windows|win32/i', $u_agent)) < $platform = 'windows'; >// Next get the name of the useragent yes separately and for good reason. if (preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) < $bname = 'Internet Explorer'; $ub = "MSIE"; >elseif (preg_match('/Firefox/i',$u_agent)) < $bname = 'Mozilla Firefox'; $ub = "Firefox"; >elseif (preg_match('/Chrome/i',$u_agent)) < $bname = 'Google Chrome'; $ub = "Chrome"; >elseif (preg_match('/Safari/i',$u_agent)) < $bname = 'Apple Safari'; $ub = "Safari"; >elseif (preg_match('/Opera/i',$u_agent)) < $bname = 'Opera'; $ub = "Opera"; >elseif (preg_match('/Netscape/i',$u_agent)) < $bname = 'Netscape'; $ub = "Netscape"; >// Finally get the correct version number. $known = array('Version', $ub, 'other'); $pattern = '#(?' . join('|', $known) . ')[/ ]+(?[0-9.|a-zA-Z.]*)#'; if (!preg_match_all($pattern, $u_agent, $matches)) < // we have no matching number just continue >// See how many we have. $i = count($matches['browser']); if ($i != 1) < //we will have two since we are not using 'other' argument yet //see if version is before or after the name if (strripos($u_agent,"Version") < strripos($u_agent,$ub))< $version= $matches['version'][0]; >else < $version= $matches['version'][1]; >> else < $version= $matches['version'][0]; >// Check if we have a number. if ($version==null || $version=="") return array( 'userAgent' => $u_agent, 'name' => $bname, 'version' => $version, 'platform' => $platform, 'pattern' => $pattern ); > // Now try it. $ua=getBrowser(); $yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " . $ua['platform'] . " reports:
" . $ua['userAgent']; print_r($yourbrowser); ?>
2) simplest function (but inaccurate for tricking) :
elseif(preg_match('/Firefox/i',$u_agent)) < $ub = "firefox"; >elseif(preg_match('/Safari/i',$u_agent)) < $ub = "safari"; >elseif(preg_match('/Chrome/i',$u_agent)) < $ub = "chrome"; >elseif(preg_match('/Flock/i',$u_agent)) < $ub = "flock"; >elseif(preg_match('/Opera/i',$u_agent)) < $ub = "opera"; >return $ub; > ?>
In PHP I use the $_SERVER[‘HTTP_USER_AGENT’] value and attack it with regex or stristr.
This may be simple way to know that the browser is not using IE, Chrome, or FF
if (navigator.userAgent.indexOf("Chrome") != -1) BName = "Chrome"; if (navigator.userAgent.indexOf("Firefox") != -1) BName = "Firefox"; if (navigator.userAgent.indexOf("MSIE") != -1) BName = "IE"; if(BName=='Chrome' || BName=='Firefox' || BName=='IE') BName="Not other"; else BName="other"; alert(BName);
function CSystemInfo() < var self = this; self.nScreenWidth = 0; self.nScreenHeight = 0; self.sPlatform = "Unknown"; self.sBrowser = "Unknown"; var init = function()< self.nScreenWidth = screen.width; self.nScreenHeight = screen.height; self.sPlatform = navigator.platform; self.sBrowser = getBrowser(); >var getBrowser = function() < var userAgent = navigator.userAgent; var version = "UNKNOWN VERSION"; if (userAgent.toLowerCase().indexOf('msie') >-1) < var ieversionreg = /(MSIE (1\.3))/; if(ieversionreg.test(userAgent)) < version = ieversionreg.exec(userAgent)[2]; >return 'Internet Explorer '+version; > else if (userAgent.toLowerCase().indexOf('firefox') > -1) < var ffversionreg = /(Firefox\/(.+))/; if(ffversionreg.test(userAgent))< version = ffversionreg.exec(userAgent)[2]; >return 'Firefox '+version; > else if (userAgent.toLowerCase().indexOf('chrome') > -1)< var chromereg = /Chrome\/(9)/; if(chromereg.test(userAgent)) < version = chromereg.exec(userAgent)[1]; >return 'Google Chrome '+version; > else return 'Unknown'; > init(); >
instantiate it by calling
var oInfo = new CSystemInfo(); // Retrieve infos oInfo.sBrowser; // Google Chrome 21
The simplest way to do it with JavaScript is
Within the location.href , you could use a PHP variable like so:
This would take a URL given as a query to the PHP script and forward to that URL. The script would be called like this:
http://your-server/path-to-script/script.php?URL_TO_FORWARD_TO
The introduction of IE 11 has made this method obsolete, though I have updated it to take that into account. It is much better to use JavaScript and feature detection. Of course, sometimes you just want to kill a browser completely and/or have to accommodate for the use case where JavaScript may be disabled.
I don’t know about the OP’s ultimate goal, but in my case all I really wanted to do was bounce Balmer’s browsers. What we had in place failed for IE 10 users due to a false positive caused by a regex similar to another solution. (I don’t know if the regex in this thread causes the same false positive or not, but I do know the one on this page is not the same as the broken one we had).
I made up a method that didn’t rely on a regex (per se). I also didn’t want to run into a scenario where I had to edit the script to accommodate new browsers, however, editing the script to expire obsolete browsers in the future is acceptable.
function obsolete_browser() < $ua = (isset($_SERVER['HTTP_USER_AGENT']))?$_SERVER['HTTP_USER_AGENT']:''; $browser = explode(';',$ua); foreach($browser as &$b)< $b = trim($b); // remove the spaces $c = explode('.',$b); // major revision only please if($c[0])< $b = $c[0]; >> if(in_array("Trident/7",$browser)) < // IE11 return false; >else if(in_array('MSIE 4',$browser) || in_array('MSIE 5',$browser) || in_array('MSIE 6',$browser) || in_array('MSIE 7',$browser) // || in_array('MSIE 8',$browser) // we'll need this soon enough, right? || in_array('BOLT/2',$browser) // worst browser ever ) < return true; >return false; >
Reliable way to detect browser , version and plattfom in php
I want to display a custom content according to these information, example :
If the user wants to know how to clear the cookies on his browser. Let’s say i have many contents already available for many browser. versions And i want to load the appropriate content automatically
Is there a way not involving Javascript to get these values?
I have use cases where the browser is not found or inaccurate. So i would like to have the most reliable solution.
Here are 2 websites that does exactly what i need :
Other link with partial solutions:
Spent many days trying, seaching, but to no success. I found many hints from Stackoverflow community:
- browsercap with get_browser(). the project was discontinued (for now 8 Aug. 2012) and doesn’t detect some modern popular handheld device.
- Javascript detect feature approach : Modernirz. Not good approach for what i want to do, to long and will have to be updated often.
- jQuery.browser Not good enough not enough possibility.
- quirksmode.org javascript and not accurate with mobile for now and would prefer PHP version.
EDIT 1 So far i have tested the answers and comments. These solutions are very satisfying:
- PHP mobile detect the last version is really good, if you are using this it would be good to give the client the form in the example so they can contribute to the project. (thanks to @Pekka)
- WURFL less recent but very good also. (thanks to @Ian Roberts) EDIT 2 PHP mobile detect uses WURFL
Make sure that the header you receive are not modified by any other library.
For example some security libraries like OWASP PhpSec [ABANDONED] change the header structure into a custom object and PHP mobile detect doesn’t have access to all the information it needs anymore
For those of you using OWASP PhpSec [ABANDONED] the http library is modifying the global header object structure. (December 2013) So if you have issues just use PHP mobile detect before you include any OWASP PhpSec class using the http library
Obtain actual browser URL in PHP
I need to retrieve the actual URL that the user see’s in their browser. I have an Ajax request running at page load. Hence, the regular $_SERVER[«SERVER_NAME»] . $_SERVER[«REQUEST_URI»] expression returns the request URL of the Ajax request instead of the actual URL in the browser. Any idea how to get this?
7 Answers 7
You could pass it up from javascript in your ajax request, using window.location.href .
Also, it’s likely that $_SERVER[‘HTTP_REFERER’] will contain the browser’s current location.
Thx for the reply. The need for browser URL is elsewhere within the code and hence passing the same via Ajax is not an option. The HTTP_REFERER does work for me. However, are there any possible inconsistencies due to which the value return could be different?
Most browsers will set the referer properly, but they are not required to do so and there’s no guarantee it will be set. If you’re making an ajax request, there should be no reason you can’t add a name/value pair to the posted variables (or even in the query string) that holds the proper URL.
Well in that case I would have to look at modifying the code and not depend on PHP server vars. Thx for explaining this.
You could also try using $_SERVER[‘HTTP_REFERER’]; . This might work, not 100% sure though.
This works for me. However, are there any possible inconsistencies due to which the value return could be different.
You can’t do that with server-side code, as there is no server-side variable that refers to what the client sees. The only thing you CAN see (and then again, it depends on the browser the user’s using, some don’t pass this info) is the HTTP_REFERRER variable. This however, is only set when a page calls another, not when users first access your site.
A possible solution however, might be to use javascript function to send the browser’s top URL to the server using an AJAX query, and to fire it client-side whenever a user loads the pages) you want to get this info for.
Edit: Damn, too slow, already answered!
Pass a hidden input that has the browser value set with your ajax request. Unless someone is being malicious, it should suffice.
If you do an Ajax-request, you could pass the address available through Javascripts window.location.href variable as a POST-variable with the request.
With jQuery it would be something like:
$.ajax(< url: 'your-url.php', type: "POST", data: < url: window.location.href >, success: function (data) < // Do something on success >>);
With such a request you could access the URL on the server-side with a simple: