Browser.php – v1.9

Browser-1-9.zip – v1.9
release: 8/20/2010
View typical usage examples
View Example Results
(view test file used in example)
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 solution but added a few things:
- I added the ability to view the return values as class constants to increase the readability
- Updated the version detection for Amaya
- Updated the version detection for Firefox
- Updated the version detection for Lynx
- Updated the version detection for WebTV
- Updated the version detection for NetPositive
- Updated the version detection for IE
- Updated the version detection for OmniWeb
- Updated the version detection for iCab
- Updated the version detection for Safari
- Added detection for Chrome
- Added detection for iPhone
- Added detection for robots
- Added detection for mobile devices
- Added detection for BlackBerry
- Added detection for iPhone
- Added detection for iPad
- Added detection for Android
- Removed Netscape checks
- Updated Safari to remove mobile devices (iPhone)
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)
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)
- 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)
- Firefox (Browser::BROWSER_FIREFOX)
- Mozilla (Browser::BROWSER_MOZILLA)
- Amaya (Browser::BROWSER_AMAYA)
- Lynx (Browser::BROWSER_LYNX)
- Safari (Browser::BROWSER_SAFARI)
- 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)
$browser = new Browser();
if( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >= 2 ) {
echo 'You have FireFox version 2 or greater';
}
12/9/2008 Update: removed an unused constant and renamed the constructor to use the PHP magic method __construct (thanks to Robin for locating the legacy constant and suggesting the use of the magic method).
2/19/2009 Update: updated typical usage to show a correct example! (thanks David!)
2/24/2009 Update: fixed typo in the usage! (thanks Adam!)
3/14/2009 Update: added support for the iPod; added iPod and iPhone as platforms; added Google’s Android
4/22/2009 Update: added support for GoogleBot, the W3C Validator and Yahoo! Slurp
4/27/2009 Update: John pointed out a terrible typo (see below) — removed the typo
11/08/2009 Update: A lot of changes to the script, thank you to everyone for the suggestions and emails. This release should add all of the requested features. Added BlackBerry, mobile detection, Opera Mini support, robot detection, Opera 10′s UserAgent “mess”, detection for IceCat and Shiretoko!
3/7/2010 Update: Version 1.7 was a *MAJOR* Rebuild (preg_match and other “slow” routine removal(s)) included the following changes:
- Almost allof Gary’s original code has been replaced
- Large PHPUNIT testing environment created to validate new releases and additions
- Added FreeBSD Platform
- Added OpenBSD Platform
- Added NetBSD Platform
- Added SunOS Platform
- Added OpenSolaris Platform
- Added support of the Iceweazel Browser
- Added isChromeFrame() call to check if chromeframe is in use
- Moved the Opera check in front of the Firefox check due to legacy Opera User Agents
- Added the __toString() method (Thanks Deano)
4/27/2010: Update (Version 1.8)
Added iPad support
8/20/2010: Update (Version 1.9) – Added MSN Explorer Browser, Added Bing/MSN Robot, Added the Android Platform, Fixed issue with Android 1.6/2.2
Pingback: The all new PHP Browser Detection | mavrick
How do I embed this code into a html file?
Hey Matthew:
The best way to embed this would be to include it from your HTML file (assuming your HTML is processed by PHP)
< ?php
require_once('Browser.php');
$browser = new Browser();
if( ! ( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >= 2 ) ) {
echo ‘You have FireFox version 2 or greater’;
}
?>
Pingback: Browser.php - version 1.1 - released! | Chris Schuld's Blog
Hi,
I’m trying to use your code but i get an error message which says “unexpecting “)”
here’s the code i put in my header php (i use wordpress)
if ($_GET["lab"]=="1") {
require_once('browser_detect.php');
$browser = new Browser();
if ( $browser->getBrowser() == Browser::IE ) {
$client_browser="_ie";
}
}
issues might be with require_once() function in accessing the browser_detect.php, and I tried to put the file in my site root and also next to the header.php which calls the browser_detect.php!
but i get the error all the time.
Please help.
Come on! I get “You have Firefox….” message even if I am on IE.
@Amir:
The unexpected “)” is likely in your wordpress file; you may want to put the Browser.php file in the same path as your template files and then call require_once like this require_once(dirname(__FILE__).’/Browser.php’);
The Browser.php file is syntactically correct so the unexpected ‘)’ is probably in your WordPress source.
@Pablo:
Can you post the user agent string for your browser? The Browser.php file is tested against a large list of agents: http://chrisschuld.com/wp-content/uploads/2008/11/useragents.txt Any chance you can post your User Agent string so I can add it into the test file? If you don’t know your user agent you can browse here: http://chrisschuld.com/myuseragent.php
Hi Chris,
This is the User Agent I get with IE:
User Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; InfoPath.2)
Hi, i have include (with require) your class into a php page, but i receive this error:
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in ***************\inc\Browser.php on line 67
(i have obscured the full url
with ***)
why?
Many thanks.
@Damien
Make sure you are using PHP5 for this class. If you are using PHP4 you should use Daniel’s PHP4 port located at: http://mavrick.id.au/programming/2008/the-all-new-php-browser-detection/
Good Luck!
I understand. In fact now the web server where my site has the 4.2 version of php. Will be updated to php 5 by Dec. 15. Pending and then you can use an excellent class, I will see the link that gave me, thanking you for your kindness
Hi !
I’m a portuguese. So, sorry my bad english
I try this script and not work with google chrome.
it’s only me ? :S
[]
If you open http://apptools.com/phptools/browser/ with google chrome, you will see “safari”.
@Miguel
The site located at http://apptools.com/phptools/browser/ is NOT running this Browser.php class at all but rather the original work from Gary White which I updated. If you want to see the execution of this class you can click here: http://chrisschuld.com/proj/Browser/test.php
This test will run the Browser class against this file: http://chrisschuld.com/proj/Browser/useragents.txt
Hey Chris,
You mentioned an easy way to embed this into an HTML file above, is it possible to use that same concept so that the browser.php detects the browser/os/ect and then redirects members using, say, Opera and Netscape elsewhere? I know its probably a silly question, but I’m fairly new to php.
Thanks in advance,
-Greg
@Greg
No chance it is a silly question
— but it does have a lot of answers, you could change the results depending on the browser you could also re-direct the user with an HTTP header redirect (301). Here is an example:
$browser = new Browser();
if( $browser->getBrowser() == Browser::IE ) {
header(‘Location: /ie’);
}
else if( $browser->getBrowser() == Browser::FIREFOX ) {
header(‘Location: /ff’);
}
else {
header(‘Location: /other’);
}
If you want my advice try as hard as you can to write your pages to the standards. Generally, this will work great and you will only have to fight Internet Explorer.
Hello,
I’m trying to do an include of this PHP page (with PHP) and it’s throwing this error:
Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively. in Unknown on line 0
Do you, or anyone else, know what’s causing this/why it is?
Well then, I guess it has nothing to do with this script. That’s odd. I never got this before…
Guess I have more work to do!
@Michael
Michael, as you guessed this error (bug_compat_42) is caused by other code in your script. The bug_compat_42 error tells me you are probably trying to assign something to your _SESSION variable in the global scope; keep digging because it’s unrelated to the Browser.php file.
Best of luck!
Very usefull code, saved me from a world of hazzle…
Only one thing that puzzle me is the typical use example which to me seems to be a faulty if sentrence. Too me it looks like it will type out the Firefox message whenever you are not using the Firefox greater than 2.0 rather then when you are actually using it?
Hi Chris,
many thanks for your & Gary’s great work. I just wonder if it wouldn’t be nice to use __construct() as the constructor name instead of Browser() – just in case people have to rename your class to match their autoloading needs
Just another question: What’s the reason for having both BROWSER_IE and BROWSER_INTERNET_EXPLORER? Seems to me that BROWSER_IE works, BROWSER_INTERNET_EXPLORER doesn’t, at least with IE7.
@robin
Thank you for your suggestions; I removed the legacy constant BROWSER_INTERNET_EXPLORER (which was not used) and added the magic method suggestion and re-released Browser.php as v1.2. Thanks!
Pingback: Updated Browser.php to version 1.2 | Chris Schuld's Blog
Hello dear mr Chris, I finally tested its excellent script and it works very well. In addition to thanking you, I wish them a question, perhaps not relevant: it is aware of a hybrid solution between php and javascript for the approval of the video resolution? I found several js script, but of course all suffer the problem of possible disabling js from the client user. Finally, I apologize for my not perfect English, are Italian.
I am getting…
“Parse error: syntax error, unexpected ‘&’ in”
I have tried in my html file
&
$browser = new Browser();
if( ! ( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >= 2 ) ) {
echo ‘You have FireFox version 2 or greater’;
}
@Violative
Can you leave some more details; the file is syntactically correct; likely the unexpected ‘&’ is coming from your HTML file in between your < ?php and ?> start/stop tags. Please post a few more details.
@Damien
Since PHP executes at the server level with relatively no connection to the user’s environment there really is no way to ascertain the user’s display information (namely: resolution). You’ll need to use Javascript to grab the information.
I will verify and retry.
Hi, thats an awsome script you have! The only problem is, im confused on how to get the browser name and put it in a variable…How do you do that?
Thanks
Hi, how do you get the browser name, and put it in a variable?
Thats the only part im confused about.
Thanks
I modified your browser.php script to add support for the browser in my T-Mobile G1 Phone (Android). Is this something that you’d like to roll into your version? If so, let me know and I can email you with the updated file.
@Rick:
Hi Rick, if you can send me the updated lines by email that would be helpful and I’ll apply it… thanks for the update/help.
–Chris
Hi,
I’m Mitul from bangladesh. i am a bigginer in php. i saw your code of browser.php. please tell me how can i see the output of this on my local browser?
thank you.
Hi Chris.
I think the “Typical Usage” is wrong becauce of the “if( !(“.
It would be great, if you could put back the netscape-browser check, because a little amount of people still using netscape.
@David:
Thank you David; you are 1000% correct; I had the bang (!) in there accidentally — that’ll teach me to cut-n-paste
@Mitul:
Hi Mitul, understood you are just starting out. Create a test.php page in the root of your web server and add the typical usage that David just helped me fix
. The file should (a) include the Browser.php class and then have the typical usage in it… then look at your page with FireFox. I hope that helps!
Hello. I am a php noob… Let’s say I’m including Browser.php in another php file, to echo the user’s browser and system. I would use “require_once”, right? What would the echo command look like? I tried echo $browser which didn’t work. Sorry for being so dumb and thanks in advance!
Thank you very much for this! It’s great! However, the “Typical Usage” is still wrong… “>= 2 ) )” has an extra closing parenthesis.
@Adam: thanks; sorry for the typo
@Max: no worries Max we were all rookies at some point…
Here is what I would suggest:
require_once('Browser.php'); // assuming Browser.php is in the same path as this script $browser = new Browser(); if( $browser->getBrowser() == Browser::BROWSER_FIREFOX ) { echo "you have FireFox"; }I hope that helps out!
Thank you a lot!
Almog Baku,
Israel.
P.S the class doesn’t detect Avant Browser..
Hi Chris,
i have problems to detect the firefox version 3.0.6 and 3.0.7. He always shows me the version 3.0.5. Do you know where is a bug?
thanks david
@David, can you post your User Agent string or visit: http://chrisschuld.com/proj/Browser/test.php
I assume it is:
Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7 (.NET CLR 3.5.30729)
But would like to make sure!
@Almog, I will look into the Avant browser; I had not heard of it until your comment; if you would like to contribute the check routine let me know.
@Chris
my User Agent is:
Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.5, Ant.com Toolbar 1.2 (.NET CLR 3.5.30729).
But I have installed the Version 3.0.7, before 3.0.6, it always tell me the 3.0.5 version. Maybe it the fault of the Ant.com Toolbar?!
I found the problem.
The Ant.com toolbar has fouled up my User Agent
How to repair the User Agent
1. Type “about:config” in the URL bar from Firefox and hit Enter
2. Look for “general.useragent.extra.firefox”
3. Right-click that preference and select Reset
4. Restart Firefox – Done!
Hi Chris
I’m a beginner at php i i was wandering:
1. what code should i use in my hmtl page
2. can i use this check to adjust a table’s height/width
Thanks in advance
Hi Chris,
Good day!
Could you by chance add “iPod” for devices to detect?
Hoping for the implementation.
Pingback: Browser.php updated to v1.3 | Chris Schuld's Blog
@Raymond
I added the iPod today as well as added both iPod and iPhone to the platform list.
Pingback: Episodes: Drupal integration & ingestor | Wim Leers
Why do I get a bunch of **s when I do echo($browser->getBrowser());
I am trying to just get the browsers name, but it gives me
** ** ** ** ** ** Firefox
Thanks!
Also, how do I get the version of the browser
Nevermind. This is what I did to get what I wanted.
require_once(‘Browser.php’);
$browser = new Browser();
$thebrowser = ereg_replace(“[^A-Za-z]“, “”, $browser->getBrowser());
$ver = $browser->getVersion();
echo “$thebrowser $ver”;
Firefox 3.0
Nice max, works like a charm :p
Very nice. Just what I needed.
Do you have any plans to add support for mail client user agents? I’m currently using this to get a list of what browsers the recipients from our mailing list are using when they load our emails, but mail clients such as Mac Mail or Blackberry are reported as ‘unknown’. Not exactly what this was intended for, but I’m just interested.
@Rich
Do you happen to have the User Agents for the different devices you could share with me and I’ll add support in for them?
It would be nice to detect major search engine crawlers (like Google Bot) and the W3C Validator bot too… This way when we validate our site or when our site is indexed, some content is fetched by the bot.
Not really important, but would be a “nice to have” feature
I found this link that might help for the W3C:
http://www.useragentstring.com/pages/W3C-checklink/
I also have a question… Is this script will continue to work with PHP 6 once released? Don’t see any reason why it shouldn’t, but just want to check…
Oops URL should be:
http://www.useragentstring.com/pages/W3C_Validator/
IS there a way to detect Netscape versions? I know it’s dead, but my website still support it (7.2 and up)…
Hello Chris,
I’ve implemented the OS identification.
Maybe you want to include it in your version too.
http://pastebin.com/f5657e881
added line 122-154 and 195-199
altered checkPlatform()
i just upload browser-v1-3.zip – v1.3 and i am getting
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in Browser.php on line 79
my code is
getBrowser() );
?>
For IE6 i used:
getBrowser() == Browser::BROWSER_IE && $browser->getVersion()
Nice work man. Really good class. I’ve used it in some of my work and I’m very pleased with the results. I hope you continue to update the browsers
@Justin
Thanks! Glad it helped you out! Before I rebuilt Gary’s solution I didn’t have a way to do this effectively either! I’m not a big fan of the PHP solution get_browser() either.
@Moises
Sounds like you are not using PHP5
@AlexV
I added GoogleBot and the W3C Validator in there. On the other hand, right now there are no plans to add in support for Netscape due to lack of demand; if you want to add them in and “patch” it to support Netscape let me know and I can put in your changes.
Also, it will work with PHP6 whenever it is production ready.
Pingback: Browser.php updated to v1.4 | Chris Schuld's Blog
What does egeg(’308|425|426|474|0b1′, $var) do on line 339? $var is also undefined.
Pingback: Browser.php updated to v1.5 | Chris Schuld's Blog
@John
Thanks and great catch. I updated the source and released v1.5. Thanks again!
Hi Chris, great script you have here. I was wondering if you were planning to add the os version detection, like distinguishing windows xp from vista
The other script I found is this one, http://techpatterns.com/downloads/php_browser_detection.php , which does detect the platform version, but the whole script is very messy and the way to use it is not as practical as yours
Anyway, I might give try at upgrading yours with this functuionnality if you don’t mind
Exceptional, I’m going to use it right now for Spargos.net.au
Pingback: Bachelor thesis finished! | Wim Leers
Hi there,
How would I implement if I want the detection to result in routing the user to another page specifically, based on the specific browser?
I’m a noob obviously.
Thanks!
Great job man ^_^
my best regards man . great works. thanks
Hi,
v1.5 has been ported to PHP4. Check it out here: http://mavrick.id.au/programming/2008/the-all-new-php-browser-detection/
@Daniel Lang
Thanks Daniel!
Very nice article.
Thanks
Rana
I’m now using Daniel Lang’s version for PHP4, but still getting the same errors I had when using the PHP5 version.
Using different bits of code from this page give different errors, for example:
require_once(“Browser.php”);
$browser = new Browser();
if( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >= 2 ) {
echo ‘You have FireFox version 2 or greater’;
}
gives
Fatal error: Undefined class constant ‘BROWSER_FIREFOX’ in /splash.php on line 7
Any ideas?
@Tim
If you are using the PHP4 version the ‘::’ before the constant is not supported in PHP4; only for a method I believe, try this:
if( ( $browser->getBrowser() == $browser->BROWSER_FIREFOX && $browser->getVersion() >= 2 ) ) {
echo ‘You have FireFox version 2 or greater’;
}
- or -
if( ( $browser->getBrowser() == ‘firefox’ && $browser->getVersion() >= 2 ) ) {
echo ‘You have FireFox version 2 or greater’;
}
- or -
if( ( $browser->isBrowser(‘firefox’) && $browser->getVersion() >= 2 ) ) {
echo ‘You have FireFox version 2 or greater’;
}
Thanks a lot,
Your class file is very helpfull.
I am so happy to get it.
brilliant, thanks for this. very easy to implement.
Thanks for the code. For BlackBerry:
protected function checkBrowserBlackBerry() { $retval = false; if( eregi('BlackBerry',$this->_agent) ) { $aresult = explode("/",stristr($this->_agent,"BlackBerry")); $aversion = explode(' ',$aresult[1]); $this->setVersion($aversion[0]); $this->_browser_name = self::BROWSER_BLACKBERRY; $retval = true; } return $retval; }Enhancement suggestion is to add isMobile property. It would make it easy to know when to optimize for small real estate screen, spotty javascript support, etc.
Thanks for the hard work,
TC
Greetings:
I had been using Gary’s original script for a while and it always worked fine I seem to be having an issue detecting the difference between IE 7.x and IE 8.x. Have you seen this or do you know of a reliable way to tell the difference?
still returns 7.0 using 8.0.
Thanks in advance and thanks for the updates to the script!
-Rob
@Rob
Did you check to make sure IE8 wasn’t running in compatibility mode for IE7 ?
Yes. I have not turned that on yet.
Right after I said that I checked again. It seems the default is to “Display all websites in Compatibility View”. Once I unchecked this it shows correctly as 8.0. Interestingly enough, when it compatibility mode the rendering was completely different then when rendered in the actual 7.0 version. .
Thanks for the tip Daniel, and thanks again for the updated script Chris and all who have added components.
-Rob
hi i have this code
curl_setopt($ch, CURLOPT_USERAGENT, “Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10″);
and this part of the code
“User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1\r\n” .
i would like to change this code to IE5 OR IE6
can you help me this will help the script that i am running suess above display but the flash player doesnt play the flv on any IE but it works great with firefox i wonder why.
@hi
Goto http://chrisschuld.com/proj/Browser/useragents.txt to get a list of known User Agents, you should be able to test out a few different 5.x and 6.x User Agents for IE.
Not sure exactly what you are trying to achieve here however remember to remove the \r\n at the end of the User Agent string you supplied. If you still have issues with flash try posting on a Flash related website or update your Flash Player plugin for IE.
Really well put together – thanks
huy chriss
i got a problem with opera mini in phone
i use this code
$browser = new Browser();
$thebrowser = ereg_replace(“[^A-Za-z]“, “”, $browser->getBrowser());
$ver = $browser->getVersion();
echo “”;
echo “$thebrowser $ver”;
but this script detect opera version 9.60
actually i use opera mini version 4.1
please help me to correct this
@Nugraha
Can you supply the User Agent string from your phone?
Great script, does exactly what I need. Thanks for spending the time to put it together.
Chris, did you received my last two email with my added features to your class?
Thanks!
Is there any plan to update this for PHP 5.3.0?
Chris,
When you get a chance, can you please add support for Iceweasel browser (http://en.wikipedia.org/wiki/GNU_IceCat). It’s actually Firefox but your class does not recognize as it.
Thanks!
Add isRobot function
Add to Constructor
/* The most common ones. The rest alphabetically. */
$this->_robots = array(‘Googlebot’, ‘msnbot’, ‘Slurp’, ‘Yahoo’,'Arachnoidea’, ‘ArchitextSpider’, ‘Ask Jeeves’, ‘B-l-i-t-z-Bot’, ‘Baiduspider’, ‘BecomeBot’, ‘cfetch’, ‘ConveraCrawler’, ‘ExtractorPro’, ‘FAST-WebCrawler’, ‘FDSE robot’, ‘fido’, ‘geckobot’, ‘Gigabot’, ‘Girafabot’, ‘grub-client’, ‘Gulliver’, ‘HTTrack’, ‘ia_archiver’, ‘InfoSeek’, ‘kinjabot’, ‘KIT-Fireball’, ‘larbin’, ‘LEIA’, ‘lmspider’, ‘Lycos_Spider’, ‘Mediapartners-Google’, ‘MuscatFerret’, ‘NaverBot’, ‘OmniExplorer_Bot’, ‘polybot’, ‘Pompos’, ‘Scooter’, ‘Teoma’, ‘TheSuBot’, ‘TurnitinBot’, ‘Ultraseek’, ‘ViolaBot’, ‘webbandit’, ‘www.almaden.ibm.com/cs/crawler’, ‘ZyBorg’,);
Add function
function isRobot()
{
foreach($this->_robots as $robot)
{
if(strpos($this->_agent, $robot) !== false)
{
return true;
}
}
return false;
}
Use of eregi() is causing warnings with PHP 5.3.0.. an update would be much appreciated!!
I got it working fine with Google Chrome but it took a little bit of working out how to do it. Did you come back with the update?
Chris,
Are you planning to update the script i.e. for Chrome and other linux distro’s like ubuntu etc? A lot has changed since April
Hi
I use Shiretoko under Ubuntu 9.04.
This is Firefox 3.5 under Ubuntu.
Change the function checkBrowserFirefox():
protected function checkBrowserFirefox() { $retval = false; if( eregi('Firefox',$this->_agent) ) { $aresult = explode('/',stristr($this->_agent,'Firefox')); $aversion = explode(' ',$aresult[1]); $this->setVersion($aversion[0]); $this->setBrowser(self::BROWSER_FIREFOX); $retval = true; } elseif( eregi('Shiretoko',$this->_agent) ) { $aresult = explode('/',stristr($this->_agent,'Shiretoko')); $aversion = explode(' ',$aresult[1]); $this->setVersion($aversion[0]); $this->setBrowser(self::BROWSER_FIREFOX); $retval = true; } return $retval; }It works for me.
Greetz M. Brotz
Would this work for BlackBerries? I’m having trouble with jQuery working on a site I built and would like to just exclude all javascript if a BB browser is detected. thoughts?
Use of eregi() is causing warnings with PHP 5.3.0.. an update would be much appreciated!!
The script doesn’t detect my Opers browser correctly. It’s version 10.00 while it shows earlier version. Code i’m using:
getBrowser().” “.$br->getVersion().” OS: “.$br->GetPlatform();
// full code at http://juozas24.puslapiai.lt/source.php?file=blah.php
?>
My user agent: Opera/9.80 (Windows NT 5.1; U; lt) Presto/2.2.15 Version/10.00
My prev post a bit messed up… That’s real Code:
require_once “browser.php”;
$br = new Browser;
ecgo “Browser: “.$br->getBrowser().” “.$br->getVersion().” OS: “.$br->GetPlatform();
// full code at http://juozas24.puslapiai.lt/source.php?file=blah.php
Hi,
Since eregi is deprecated in php 5.3, could you replace eregi with suitable regex
@ALL
I am testing and have a new version of Browser.php coming that supports PHP5.3. Sorry all; I have been busy converting a few other projects to 5.3 … an update is near!
thanks for the heads up chris,
mainly all occurences of eregi need to be replaced with preg_match
just updated my local test server to 5.3 and i get all sorts of errors
commented out any libraries that are not essiential and will try and update them all later on, hopefully will have a fresh copy of yours in a few days
@Chris
Any Idea if Google Chrome Frame will alter the USERAGENT? http://code.google.com/chrome/chromeframe/
@Daniel
Hey Daniel! Hope you are well! From what I can tell so far (as of the latest version) Google Frame uses the IE6 USERAGENT on the server side but adds “googleframe” to it. (side note: I am going to add it into Browser.php) The client side sees the browser as Google Chrome ironically.
I have the PHP5.3 version ready with bunch of updates — I will add this in as well. Just need to find some time to get it online!
chromeframe will be used as i have read for Google Wave, they have decided to focus on safari,firefox,chrome and leave out IE since it would take a lot of development time. chromeframe should render a page using chrome rendering engine and therefore should identify itself as Google chrome.
thanks for getting a PHP 5.3 version ready chris, will sure grab a copy once its online.
@Chris
Glad to see you’re still advancing on the Browser Detection script, I look forward to porting it back to PHP4.x
Did a little reading up on Google Frame and didn’t hesitate to install it
Shame it doesn’t seem to work on IE8 Win7 64bit!
@Paris
From what I understand the whole idea of Google Frame was to make IE6,7,8 play ball with web standards and actually support standard html tags properly?
Anyways, would be nice to detect if a user has it installed or not
Windows XP SP3 Build 2600 – IE v7.0.5730.13
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6; chromeframe; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Script doesnt track the latest version of Opera properly. Returns a different version number rather than 10.0
I tried to use Browser.php on my website, which is hosted on Unix Operating System, it does not work. any idea? the following is the code:
getBrowser() == $browser->BROWSER_FIREFOX && $browser->getVersion() <= 4 )
{
echo "”;
}
elseif( $browser->getBrowser() == $browser->BROWSER_OPERA && $browser->getVersion() <= 10 )
{
echo "”;
}
elseif( $browser->getBrowser() == $browser->BROWSER_IE && $browser->getVersion() >= 8 )
{
echo “”;
}
elseif( $browser->getBrowser() == $browser->BROWSER_IE && $browser->getVersion() == 7 )
{
echo “”;
}
elseif( $browser->getBrowser() == $browser->BROWSER_IE && $browser->getVersion() == 6 )
{
echo “”;
}
elseif( $browser->getBrowser() == $browser->BROWSER_SAFARI && $browser->getVersion() <= 5 )
{
echo "”;
}
elseif( $browser->getBrowser() == $browser->BROWSER_CHROME && $browser->getVersion() <= 4 )
{
echo "”;
}
else
{
echo “”;
}
?>
thanks
Sorry here the code again…
getBrowser() == $browser->BROWSER_FIREFOX && $browser->getVersion() <= 4 )
{
echo "”;
}
elseif( $browser->getBrowser() == $browser->BROWSER_OPERA && $browser->getVersion() <= 10 )
{
echo "”;
}
elseif( $browser->getBrowser() == $browser->BROWSER_IE && $browser->getVersion() >= 8 )
{
echo “”;
}
else( $browser->getBrowser() == $browser->BROWSER_IE && $browser->getVersion() == 7 )
{
echo “”;
}
?>
functions eregi() and ereg_replace() have been removed from PHP 5.3 !!!!!!
You forgot blackberry
FAIL
Hey Chris, thanks for this amazing script.
The only problem I seem to be having with it is when I upload it on the server, it gives me this error:
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in C:\Inetpub\vhosts\l2-standard.com\httpdocs\_common\_php\browser-detection.php on line 86
Am I doing something wrong or is there something wrong with my host? And is there any way this can be solved?
Thanks, windguard
Hi Chris,
I know you’re busy, but do you have an estimate as to when you might have the new version online? I would love to have the update and I’m sure everybody else would too
Hey!
Just found this forum, Chris, please inform me when you have your script up… I’m so frustrated, each browser shows a site different… !
Pingback: Opera 10’s User Agent | Chris Schuld's Blog
Hello Everyone,
Thank you for your emails about the Browser.php project. I am SO SORRY for the extended delay; all of my time has been eaten by work! I just posted the latest version of 1.6 for you! Here are a few notes, kudos and comments!
@Daniel Lang – Daniel: thank you for your continued help!
@Saidur, @Nayan, @Callan Winfield, @Ken, @Nick: Thank You — glad you enjoyed the Script
@Topher: thank you for the code snippet for BlackBerry, I updated the calls for PHP5.3 and added it in!
@Alex: Alex, Netscape Navigator and it’s odd re-versioning are included in this version as well
@Jeff: I’ll try to add all of the crawlers you provided; thanks!
@Nugraha: Opera Mini is now in version 1.6+ (thanks!)
@Ville, @Reiborn, @Sanjay: thanks, PHP5.3 version has been in the works for a while, here it is finally!
@Manuel: thanks for the code, I added full support for Shiretoko
@Andrew Mellenger: it now has BlackBerry support, thanks
@Juozas, @William: agreed, Opera 10 has a unique User Agent story, but this version (1.6+) fixes this problem
@Nick: grow up
@Adam and @Mark — thanks for the final push
The 1.6 release adds support for the following:
PHP 5.3, Opera Mini, BlackBerry (as a platform and as a browser), IceCat, Shiretoko, isRobot(), isMobile(), support the deprecated Netscape Navigator version 9, Opera version 10, and additional documentation
Pingback: Browser.php updated to v1.6 | Chris Schuld's Blog
And ported to PHP4.x =D
http://mavrick.id.au/programming/2009/php-browser-detection-script-v1-6/
Enjoy!
oOooOo haven’t seen this one yet: Mozilla/5.0 (compatible; Google Desktop)
Here is a suggestion, detect if they have a certain .NET version.
If I send the function “3.5.0.0″ then return true or false if they at least have that version installed.
Example,
http://msdn.microsoft.com/en-us/library/bb909885.aspx
Pingback: Jason Antman’s Blog » Android links - maps, dial a phone number
Nice work with this script. I was using the original script by Gary White but that one doesn’t work with PHP 5.3
@Daniel Lang: Thanks for the PHP4 version too!
Thanks for update. Now the script detects browser correctly.
Hi Chris,
I would be interested to hear your thoughts on handsetdetection.com if you get the time..
David
Pingback: PHP探路者
@David
Seems dodgy… just my $0.02
We’re looking at including a better mobile base detection for this script, be sure to check back for more information at a later date
Hi!
That is really a great effort to help us.
Thanks.
regards,
khurram shahzad
Hi Chris,
Looking at your script, it is very nice, but might I make a small suggestion? There is a massive usage of preg_match, where something like stripos would do? Is there any reason for this? – stripos being usually a far faster solution, anyone looking at saving processing power in big scripts should consider this!
example:
if( preg_match(‘/blackberry/i’,$this->_agent) )
could be:
if(! stripos($this->_agent, ‘blackberry’) === false )
it achieves the same effect, and my execute faster, but does take a little extra typing!
Just a thought.
Regards,
Ollie
@Ollie
I completely agree; all of the preg_match syntax is legacy from the previous content owner. I 100% agree it needs to be fixed… just an equation of time to dedicate to it (including testing). Next time I rev it I’ll remove some of them! Soon it will be fixed
Thanks Ollie!
Iceweasel support (full open source firefox)
[php]
/**
* Determine if the browser is Firefox or not
* @return boolean True if the browser is Firefox otherwise false
*/
protected function checkBrowserFirefox() {
$retval = false;
if( preg_match(‘/Firefox/i’,$this->_agent) ) {
$aresult = explode(‘/’,stristr($this->_agent,’Firefox’));
$aversion = explode(‘ ‘,$aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_FIREFOX);
$retval = true;
}
if( preg_match(‘/Iceweasel/i’,$this->_agent) ) {
$aresult = explode(‘/’,stristr($this->_agent,’Iceweasel’));
$aversion = explode(‘ ‘,$aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_FIREFOX);
$retval = true;
}
return $retval;
}
[/php]
Version 1.6 is great! However, I had the following message come up in my error log a few times:
PHP Notice: Undefined offset: 1 in [path]\Browser.php on line 664
This is the line:
$aversion = explode(‘ ‘,$aresult[1]);
This is the context of the line:
protected function checkBrowserFirefox() {
$retval = false;
if( preg_match(‘/Firefox/i’,$this->_agent) ) {
$aresult = explode(‘/’,stristr($this->_agent,’Firefox’));
$aversion = explode(‘ ‘,$aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_FIREFOX);
$retval = true;
}
return $retval;
}
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Avant Browser; Avant
Browser; .NETCLR 2.0.50727) probably MSIE version 6.0 running on Windows
That’s Avant
Chrome Frame add the string chromeframe to the agent of IE. It will be great if you add this to the class.
Thanks
Hi Chris,
Thanks a lot for this amazing script.
:Binish Philip
great job, dude!
Thank you for this. It represents a ton of work that you have done and is very useful.
very usefull script. thank you very much. thank you so so so much
Hi,
I do understand it is a lot of work to maintain such a script so why don’t you put it on a open github repo so that people can easily collaborate and improve the code ?
BTW, thanks for the script
I have done a few changes to get the browser.php ready for the iPad OS and iPad Mobile browser, and I uploaded the code to http://img.hankweb.com/browser.zip for anyone who would like to have iPad support. Everything is still in the same format.
I need help, i added the code for google bots but its not detecting it, can you please give me a hint what might be the problem.
Thank you
Hey Chris thanks for the info and the script. I have $browser in use on my site and it’s still not fully implemented yet. I know a lot of programming languages and PHP is easy for me to understand but my question is this, what is it best used for? Anyways thanks again. Keep going.
Mark
Thank you so much Chris!
By the way, I found something really useful and something many people would want;
Similar code to:
$browser_name = $browser->getBrowser();
$browser_ver = $browser->getVersion();
echo “You are using ” . $browser_name . $browser_version;
Will output something like this:
You are using Safari 4.0.1
That code could also be used in simpler if statements like this:
if($browser_name == “Safari” && $browser_version == “4.0.1″)
{
“Hey there! You are using Safari 4.0.1!”
};
Hope this helps
Thank you very much again Chris!!
Is it work in Nokia mobile browser? I was trying to use the script using $browser->getBrowser() == Browser::BROWSER_UNKNOWN but it didn’t work. CMIIW.
Thanks.
Pingback: Browser Class « Nous | Webbie
NICE CLASS
Hi chris
Very good work
I noticed that recently (in some cases) unknown browsers have increased up to 90%, especially visitors from the United States
this is explorer 9?
is there any way to fix?
Pingback: PHP ile Mobil Sayfalar
Pingback: Yusuf Ali Bozkır – Günlük » PHP ile Mobil Sayfalar
Hey I’ve not yet had a chance to put this class into action in my projects, but I wanted to let you know of something which I found with the current release that I’m assuming is erroneous…
I’m assuming my text editor opened the file with the wrong encoding type because there were little squares all throughout the document where line breaks should have been… However, after cleaning all that up and re-tabbing everything, I noticed on line 680 that there is a stray “echo” which doesn’t actually do anything…
Here’s the full function it’s in (along with the echo)
protected function checkBrowserMozilla() {
$retval = false;
if( preg_match('/mozilla/i',$this->_agent) && preg_match('/rv:[0-9].[0-9][a-b]?/i',$this->_agent) && !preg_match('/netscape/i',$this->_agent)) {
$aversion = explode(' ',stristr($this->_agent,'rv:'));
preg_match('/rv:[0-9].[0-9][a-b]?/i',$this->_agent,$aversion);
$this->setVersion(str_replace('rv:','',$aversion[0]));
$this->setBrowser(self::BROWSER_MOZILLA);
$retval = true;
}
else if( preg_match('/mozilla/i',$this->_agent) && preg_match('/rv:[0-9]\.[0-9]/i',$this->_agent) && !preg_match('/netscape/i',$this->_agent) ) {
$aversion = explode('',stristr($this->_agent,'rv:'));
preg_match('/rv:[0-9]\.[0-9]\.[0-9]/i',$this->_agent,$aversion);
echo
$this->setVersion(str_replace('rv:','',$aversion[0]));
$this->setBrowser(self::BROWSER_MOZILLA);
$retval = true;
}
return $retval;
}
I am new here and did not read all the comments or the code Chris gave, but if you just want to find if the user’s browser is one you like, perhaps you could do this. (These browsers have support for @font-family and support for ligatures — the two things I want for my project).
=======CODE SAMPLE=========================
I like this browser!
Uh, oh. Maybe you should get one of these:
Firefox, Safari, Lunascape or Arora.
=======END CODE SAMPLE=====================
Hello Chris!
I like your PHP Web browser detection class, but unfortunately it lacked some features I needed badly so I modified your class to add what I needed.
I took most of the week to revise the current version and to test my new features. I tested all the known versions of the following browsers with your class and my new improved version: Internet Explorer, Firefox, Safari, Opera, Chrome, Netscape and Mozilla.
This is the number of different User Agents I’ve tested with your class:
Internet Explorer tests: 3695
Netscape tests: 668
Mozilla tests: 505
Firefox tests: 4101
Safari tests: 650
Opera tests: 1173
Chrome tests: 375
Total: 11167
With your class v1.6 I’ve got 1358 errors (12.16%). With my version: 0.
What is lacking with 1.6 that I’ve added/improved:
- The class is not able to detect Safari < 3.0 since it's not in the UA. I did some research and added the support to all version < 3.0 (0.8 to 2.0.4).
- Added support of all Netscape versions (1.6 only supports v9).
- Better Firefox version parsing (in some rare/weird UAs the class don't parse correctly the version).
- Better (more precise) Opera version parsing.
- Rewrite of Mozilla detection function for better (more precise) results. FYI the current version also contain a bogus echo and a useless else statement (remnant of debug code?).
- In some unusual case Firefox, Netscape, Mozilla, Chrome, Opera can be mixed up. I fixed this.
- Fixed some place where the code issued a warning (using inexistent array indexes).
I will email you my changes (and my 11K+ tests) if you want to check & add them to your class.
Thanks!
Alexandre Valiquette
Wolfcast
Quebec, Canada.
Hai, this is very amazing script. it’s very useful for my site. Thanks a lot.
nice work….i like your scripts Chris…keep up
Version 1.8 released… version 1.7 was a massive re-write and v1.8 added iPad support! Thank you for all of the comments and suggestions!
The isRobot check only appears to be checking for Yahoo!, Google and W3C. Shouldn’t you also add the MSN bot which powers Bing? Something like:
protected function checkBrowserMSNBot() {
if( stripos($this->_agent,’msnbot’) !== false ) {
$aresult = explode(‘/’,stristr($this->_agent,’msnbot’));
$aversion = explode(‘ ‘,$aresult[1]);
$this->setVersion(str_replace(‘;’,”,$aversion[0]));
$this->_browser_name = self::BROWSER_MSNBOT;
$this->setRobot(true);
return true;
}
return false;
}
Amazing script! Simple, but very useful and accurate. Much better than all the other similar scripts I have seen that were very unreliable. It’s exactly what I need – keep up the good work with updating it!
very amazing, thanks!
Pingback: Q Flash header vervangen voor iPhone users - 9lives - Games Forum
hey,
great work! try it now and works good.
but one bug i found, milestone mobile with android browser is detected as safari, platform linux and is_mobile = 0
Will work on the PHP4.x port soon
seems like it is mis-identifying the andorid browser as safari, at least in the SDK emulator.
Chris -
Thanks for the code. One problem – Android and I think iPad return ‘Mobile Safari’ in the user agent string (my test iTouch works, tho). Thus, checkBrowsers finds Safari when using Android, and quits…with mobile set to false. Two ways around this:
- move section in checkBrowsers that looks at mobile devices (Android thru Nokia) above first section (WebTV thru Safari)
- add ‘Mobile Safari’ check above Safari check
Former results in browser identified as being Android, latter would result in browser identified as Mobile Safari.
+1 for android support, current release says it is not mobile and got the browser wrong
. Fantastic script though, thanks for the post!
Extremely usefull and reliable. Thanks mate:)
You might want to check WURFL (http://wurfl.sourceforge.net).
That is a powerful and very deep browser capability database along with an API in different languages that help on device detection.
The approach in this might be OK for desktop browsers. But trying to identify capabilities on Blackberry or iphone? Go WURFL for anything mobile.
Cheers
Mario
Hello All:
Version 1.9 is now out that addresses all of the input! Thanks for the comments and emails!
–Chris
Fantastic class!
By far the most expansive, best and complete way to detect browser, version and os. And best of all – it’s implemented in my own website in under 2 minutes. Thank you very VERY much for putting this out here!
Regards, Matthijs
Thanks for your great work! I have put this into a extension for the Open-Source-CMS Contao. This makes it easily available for all Contao developers.
Thanks alot, it works alot better than a class called PHP Sniff that I was using before (Outdated I think).
Just tested it in I.e. 6, 7, 8, 9 (BETA) and Firefox 3.6.8 + 4(BETA), Chrome (V???) and the detection works correctly for every single one.
Wonderful work and thank you for your continued efforts to keep it compatible. It also intergated into my existing framework with less than 5 line changes to coding. =)
I want to detect first if the browser isMobile() and then if it is an iPhone or an iPad.
The function isMobile() works good. but if i want to implement the function checkBrowseriPhone() i get an error.
Can you tell me how i have to write the php code.
here is my poor version (absolutely beginner, sorry):
$browser = new Browser();
if( $browser->isMobile()) {
echo ‘you are on a mobile device’;
if ( $browser->checkBrowseriPhone()) {
echo ‘you are on an iPhone’;
} else {
echo ‘you are on an other mobile device than iPhone’;
}
} else {
echo ‘you are NOT on a mobile device’:
}
I get an error at the statement: if ( $browser->checkBrowseriPhone())
please give me some advice. thx in advance
Hi Dev,
Yes, do this…
$browser = new Browser(); if( $browser->getBrowser() == Browser::BROWSER_IPHONE || $browser->getBrowser() == Browser::BROWSER_IPAD ) { echo 'You are on an iPhone or iPad'; }Hello!
Thanks for the class, it’s very usefull and works fine. I use it for creating visitors stats, in a larger web aplication wich captures also the visitor operation system and version, sections visited and so on.
If you just want to get the browser details using this class, you should have something like this:
getBrowser();
$browserVersion=$browser->getVersion();
?>
Thanks again for this class.
Hai,
Could please tell me how to write a simplified OS Detection script in php, OS Detection in the sense,that user is using or viewing what OS may be ANdroid, Windows Mobile, Linux,
Desktop/Laptops OS, Smartphone OS/Mobile OS, Notebook OS…
and please be in step by step
Brilliant work. Thank you very much for this class. I hope that this helps. I have noticed a small typo in version 1.9. Line 251 refers to ‘browser’ rather than to ‘platform’.
Once agaon thanks for this excellent class.
Regards
Vincent
You should consider session-based storing implementation using __sleep() and __wakeup because the current solution isn’t scalable at all.
Hi Kemal,
Thank you for your comment, however, I disagree with your suggestion. The Browser.php implementation is strictly a utility class to do the “calculation.” How you implement your scaling, session storage, or even use Browser.php is up to you as the author of your solution. Personally, I would only load the Browser.php file once to do a single calculation per visit rendering the __sleep and __wakeup (magic functions) worthless. Let me know if you feel I am off base.
Thanks, Chris
Pingback: Kirk Holmes Blog » Blog Archive » Browser.php – Detecting a User’s Browser From PHP
Hey Chris,
I implemented a small fix in the code. This checks for the Facebook user-agent (referenced when sharing links to Facebook):
// in vars
private $_is_facebook = false;
// constants
const BROWSER_FACEBOOK = 'Facebook';
// add to checkBrowser()
$this->checkBrowserFacebook()
// main function
protected function checkBrowserFacebook() {
if( stripos($this->_agent, 'facebook') !== false ) {
$aresult = explode(' ', $this->_agent);
$aversion = explode('/', $aresult[0]);
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_FACEBOOK);
return true;
}
return false;
}
This usage can be referenced here….
http://www.facebook.com/externalhit_uatext.php
~ Andrew
Pingback: PHP IE6: upgrade boodschap - 9lives - Games Forum
I recently had to use your script. My client wanted his page to display content specific for the platform.
Your code is easy to use, easy to understand, and it works!
Hi,
I get “Apple” as platform and “Safari” as browser when using Android 2.2. Is that normal? Does it have anything with webkit to do?
Hmm, seems like when you uncheck the setting to “show mobile pages”, android enforces Apple and Safari as platform and browser.
huh..
any way to get past that?
Sehr cool. Danke. Sowas habe ich gerade gesucht.
love this class – saved me lots of time. the only thing i have modified is to add a major version attribute of the class. so instead of the code having to parse the version string, i can access the major version of the browser instantly.
i added
private $_majorversion = 0;
and in the determine() function i added the following to the end of the function:
if ($this->_version != ”) {
$a_versiontemp = explode(“.”,$this->_version);
$this->_majorversion = $a_versiontemp[0];
}
and added the getMajorVersion public function. this allows me to get know if it’s IE6 or IE8 instantly in the code.
cheers!
Hi Chris,
One good thing about you is that, the great code is not just out there, but you response to average learners like me,
@GRAHAM, I have been reading the wonderful comments, GRAHAM added this comment “love this class – saved me lots of time. the only thing i have modified is to add a major version attribute of the class. so instead of the code having to parse the version string, i can access the major version of the browser instantly.
i added
private $_majorversion = 0;
and in the determine() function i added the following to the end of the function:
if ($this->_version != ”) {
$a_versiontemp = explode(“.”,$this->_version);
$this->_majorversion = $a_versiontemp[0];
}
and added the getMajorVersion public function. this allows me to get know if it’s IE6 or IE8 instantly in the code.
cheers! ”
However, I tried to used and failed, is there a chance you can explain this please and how it can be used. Because GRAHAM’S work is incomplete, some of us are novices and needs to be coached every detail. Many thanks.
You rock! Saved me a ton of time!
Pingback: All Browser CSS Hack « KaixersofT { ScriptBlocK } Weblog
Pingback: Browser.php – Detecting a User’s Browser From PHP | United Eagle Technologies
Thanks, Chris Schuld, for your PHP class. It’s the really greate tool for “webmaster”.
Hi Chris,
I am a student learning PHP, I want to learn how to detect users browsers, I came across your class on Google. However I am having difficulty using it. I will like to know how I can detect the browser, Can I simply call a function like: getBrowser(); can you please send me the syntax please.
@Julius
Please see the example usage above; that will help!
Example:
require_once "browser.php";
$b = new Browser();
echo $b->getBrowser();
Many thanks for your help. It works. I am very grateful, you have a great code. I applaud your vision, thinking and knowledge. I can now modify it to suit my purposes.
A suggestion Chris, can you rewrite this great code in your next updated, using the dot(.) operator to call objects please. The reason is new students of my era are thought in classrooms with the dot operator, and I know a lot more students out there when they see your code, they will love to use it, but will be limited to understanding it since your are using -> operator to call the object. Once again many thanks for your help.
Chris,
This is great code dude. I admire genius like you, that gives me the edge to learn and study, I also appreciate people sharing their knowledge so that we all will be knowledgeable. I will try and understand the class browser.php.
nice! works very fast, some small issues with version detection, but it is not a big deal.
I parse huge logs and did not found any better solution than your class, original browscap is very very very slow!
Hi,
I’m a Joomla developer and used your script in one of my plugins!
It is working very well, without any bigger trouble!
Thank you for that great work!
Maik
Hi Chris,
Any chance you would you consider releasing this handy code in GNU Lesser General Public License?
Fantastic work! Thank you so much for this. It correctly identifies my Android 2.2 OS as well as Chome.
Hi Chris,
Great Work!
Im a newbie to php and trying to figure out how to put a message for IE6 users while further down the page reuse the script to have another if statement to show content for windows OS only.
thanks again!
Never mind Chris,
With some digging around figured out what I was doing wrong.
Many thanks, works like a dream
thanks for the code
Hi,
I am trying to find out why this php code works on my local machine and doesn’t on the server. I guess it’s cuz I have php5 and the server may have php4, but i cudnt find the server’s php version, so I am not sure. Can you please tell me if that’s that only reason that the code might not work on the server and if that’s the case is which part of the php codes are not recognized by php4?
Thanks
totally forgot about this phpinfo(); code :-p
yeah unfortunately is 4.3.9
any suggestion?
Awesome library Chris! Worked perfectly for what I needed. Many thanks.
Great job Chris, its so useful. I’m using this class now. Thanks.
Hi, I have Added getPlatformVersion(); as a function, it returns what windows version the user is using, supports
Windows CE
Windows 95
Windows 98
Windows nt4
Windows 2k
Windows 2k SP1
Windows SERVER 2003
Windows XP
Windows Vista
Windows Seven
This version can be found here: http://pastebin.com/QzzkwLu6
Sorry For the double Post, missed something out in the php source on the first one
Hi, just a little word to say that I use this class and it works perfectly. I use it for logging purposes only, but that’s still nice. Good browser detection, even recent ones.
Thanks!
Hi
I want to use this Browser detector to limit how many members are listed on IE browsers as I have an issue of timeouts on that browser
I have code like this
————————-
$browser = new Browser();
(Line 1592) if( $browser->getBrowser() == Browser::BROWSER_IE)
{
$listLimit=100;
}
else
{
$listLimit=301;
}
Line 1952 is the one causing an error on my live site but it works fine on my test site running on a local apache server. Both live and local versions of the site use php5
The error on the live site is
Parse error: syntax error, unexpected ‘)’, expecting ‘(‘ in /homepages/10/xxxxxxxxxx/htdocs/forums/memberlist.php on line 1592
I have uploaded the Browser.php to my live site same as I have on the test site
All files are in the same relative folders on both sites
Yet as I say it works fine on my test site (and was very easy to implement) so I really don’t really know where to start. I’ve re-downloaded the uploaded memberlist.php file and tested it again on my local test site – just to be sure it was not getting corrupted during upload – which of course it was not.
This is the first time I have ever come across a file that works on test but not on live site so I’m a bit baffled
In anticipation of a useful response
Rich
Oh of course the (Line 1592) is not in the code – it is just to illustrate here which line causes the error
Thanks a million Chris…
This post was very very useful and saves me lot of time…
thanks so much for writing this class, this is an issue that only ever comes up around site-testing, and its such a chore, this class makes it sooo much simpler. nice work.
Any idea if you plan on including webOS to the list?
Nice code Chris! Thanks for make it public.
Work beautifully with my cakephp website! Thanks very much, Chris!
@ Chris
Thanks for sharing the class, it worked like a charm.
@John B
Nice addition, thanks.
Excelent work….
Hi!
First off, thanks for your code! We use this script all the time and it works great.
Today though, I ran into a teeny tiny issue: I’ve been generating html documentation for all the code we use, and your script causes some errors because of the placement of the package tag. Apparently, annotations like @param and @package are multi-line and should always come at the very end of a comment. This means a valid documenter interprets your entire copyright text, typical usage etc as the package name.
I’ve “fixed” this in our local copy, but it won’t be too long before someone replaces it with the next version you release
Thanks again,
Michael
move it to github!
Thank you so much for this script….very useful. much appreciated.
Thank you so much Chris!! And thank you also for getting back at the comments. I got a lot of my question covered by that
best greetings from austria
Hi Sir, it works good for the moment, and allow me to offer another option seen the problems caused by IE (a real nightmare every time) with Uploadify plugin.
Thank You much and merry christmas from Italy
Thanks very much for maintaining this class, it is a great help.
I sent you a personal mail about a bug in the class, but was not sure if that was the best method to report issues to you. It had to do with the Microsoft emulator for the Mobile PC platform.
If this is not the best way to contact you for issues, please let me know if there is a better way, or if I should fix the code and submit the change to you some how? Thanks again for the class.
A great library but im wondering if u add a functionality to check if javascript is enabled or not in user’s browser.
Pingback: یافتن نام و مشخصات مرورگر بینندگان سایت شما به وسیله php و کاربردهای آن « یک طراح وب
Pingback: ブラウザ情報を検出するライブラリ「Browser.php」 | Web活メモ帳
Pingback: Browser detection in PHP | Mr.Webmaster – Blog
Pingback: Asal Yazılım » PHP ile Mobil Sayfalar
Pingback: Browser Detection With PHP – Browser.php
Pingback: Browser.php: Riconoscere la versione del Browser in suo
Pingback: Browser Detection With PHP – Browser.php » Turkpixel
Sorry for the bad English but I’m using google translate.
I wanted to ask if you could add between broswer recognized “W3C_Validator”, “facebookexternalhit”, “Googlebot”, “YandexBot”, “Google Web Preview” or operate them separately to avoid putting themselves in the UNKNOWN
I have a question. I really like the script, highly effective. I need to discover the language currently set. Have you thought about this? Any suggestions to anyone who has.
Pingback: Определение браузера с помощью PHP – Browser.php « Русское Web-депо
Thanks, this script using for web statistics.
Very awesome post. I simply stopped by by your website and wished to state that I’ve truly loved browsing your posts. Any method, I’ll be subscribing to your RSS feed and in addition I hope you submit again quickly!
Hi Chris,
Just wondering if this script is able to detect the following mobile browsers:
1. Opera mini
2. Opera mobile
3. Palm OS
4. Windows mobile
Cheers,
Vince
I just tested the script on my Android smartphone and discovered that all the browsers I use on my phone are detected as Android platform.
That is actually a better solution for me than to try to detect the individual browsers like Dolphyn, Opera and Android browser!
Right now, my main concern is the Windows mobile browser. Some years back, there were these Pocket PC and Palm devices. I wonder if this script can detect those as well?
Thanks for the script, took me 30 minutes to configure, mostly because I don’t speak fluent php (speak it with a Java accent).
really good script indeed!
!
you saved me
thank you so much for this class
cheers
My Nokia C6 is a Symbian S60v5 but appears as not mobile, because de IF verify before if “Nokia” is in the user agent, and into the IF verify if is a Symbian. It’s a bug, see above:
protected function checkBrowserNokia() {
if( preg_match(“/Nokia([^\/]+)\/([^ SP]+)/i”,$this->_agent,$matches) ) {
$this->setVersion($matches[2]);
if( stripos($this->_agent,’Series60′) !== false || strpos($this->_agent,’S60′) !== false ) {
$this->setBrowser(self::BROWSER_NOKIA_S60);
}
else {
$this->setBrowser( self::BROWSER_NOKIA );
}
$this->setMobile(true);
return true;
}
return false;
}
I did a workaround:
protected function checkBrowserNokia() {
if( preg_match(“/Nokia|Symbian([^\/]+)\/([^ SP]+)/i”,$this->_agent,$matches) ) {
$this->setVersion($matches[2]);
if( stripos($this->_agent,’Series60′) !== false || strpos($this->_agent,’S60′) !== false ) {
$this->setBrowser(self::BROWSER_NOKIA_S60);
}
else {
$this->setBrowser( self::BROWSER_NOKIA );
}
$this->setMobile(true);
return true;
}
return false;
}
I’m reporting the following bug:
$browser = new Browser ();
$browser->setUserAgent (“BlackBerry9700/5.0.0.593 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/603″);
echo $browser->getVersion();
// returns “5.0.0.593″ — CORRECT
$browser = new Browser ();
$browser->setUserAgent (“Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en-US) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.246 Mobile Safari/534.1+”);
echo $browser->getVersion();
// returns “534.1″ — INCORRECT. It should return “6.0.0.246″
Nice class!
Great work man!
Awesome! just what I was looking for, started writing a similar class my self, but than I stumbled across this and it’s perfect. Thank you so much!
Pingback: 2xml.co.uk » Browser detect
php, yeah. Have been looking for this information a while.
Pingback: Anonymous
Jop, the Browser.php is realy a very usefull PHP class but you can detecting a users browser also with other php code snippets but I hope my favorite browsergames will not do that^^ .. the question is, runs this php class also if i use a other useragent? Thanks for your article
Thank you for this great utility class!
Hi Chris
Thanks for this class
I’m new in php, how to get the version of the OS ? Windows XP, 7, etc
Thanks
Pingback: Detect Browser PHP Script – Browser.php | AbyYaar
Pingback: Media Queries – Ideas & Inspiration
Thanks lot for this usefull post..
Thanks lot.
Full Bots list: http://www.gisher.ru/bots.php
great script! Thanks for sharing
PHP4 version made for v1.9
http://mavrick.id.au/browser-v1-9.rar
http://mavrick.id.au/browser-v1-9.zip
Enjoy
Browser for iPhone is returned as “iPhone”, when it should be “Safari”.
UA is:
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5
Also, _os always seems to come back blank. Useful snippet here for detecting:
http://www.geekpedia.com/code47_Detect-operating-system-from-user-agent-string.html
Hope that’s of some use.
And thanks to Daniel for sending over a PHP4 version (I know!) from:
http://mavrick.id.au/browser-v1-9.rar
http://mavrick.id.au/browser-v1-9.zip
-or-
http://mavrick.id.au/browser-v1-6.rar
Pingback: Image upload Script with thumbnailing – Kungmania Upload Script « kungmania
Brilliant! works perfectly for me (2011-06-15)
Ultimate class for browser detection
Thanks Chris!
Pingback: Anonymous
Very useful class! but I’m not able to detect iphones, ipad version.
can’t wait for version 2.0 to be release, Keep up that good work.!!
Thanks! I was using a Browscap script before, but despite being updated frequently by it’s maintainer, it could not identify current FF or Chrome. There were others that I googled and found and implemented that stunk too. Yours is simpler and just works! Thanks!!!!
Pingback: О проекте Все бланки | Serge Bezborodov - блог веб разработчика CakePHP, Yii framework
Hey Chris,
First of all, thanks for the great work on that piece of code! We’re happy users
Just wanted to report a bug that appeared in our logs, I guess it’s an issue of an updated AOL user agent string causing Browser.php to throw errors:
Undefined offset: 1, /www/[...]/Browser.php, 435, Array ([aversion] => Array ([0] => aol/http))) called at [/www/[...]/Browser.php:435]
I hope we can get a fix sometime, that would be awesome!
regards,
mike
Excellent script. It is really very usable PHP class to gather data about Browser and OS.
Thanks for the class, i am using it for my themes and templates to add the conditional styles (especially for internet Explore
)
Google Rich Snippet use User agent: Googlebot-richsnippets
So, NOTICE messages were raised in line 447. So checkBrowserGoogleBot function need fix as following:
protected function checkBrowserGoogleBot() {
if( stripos($this->_agent,’googlebot’) !== false ) {
$aresult = explode(‘/’,stristr($this->_agent,’googlebot’));
$aversion = isset($aresult[1]) ? explode(‘ ‘,$aresult[1]) : array(0);
$this->setVersion(str_replace(‘;’,”,$aversion[0]));
$this->_browser_name = self::BROWSER_GOOGLEBOT;
$this->setRobot(true);
return true;
}
return false;
}
Pingback: Browser.js – A JavaScript alternative to Browser.php | Tims Tech Blog
Here’s a JavaScript version that I whipped up. http://www.golen.net/blog/browser-js-a-javascript-alternative-to-browser-php/
Working on an updated version for PHP5 and PHP4
btw, this works for Firefox (replace “IE” with “FIREFOX” and “7″ with “5″