Page 1 of 1

PHP Browser Detect

Posted: Tue Dec 06, 2005 8:33 pm
by VKX
I want to say

if (browser is internet explorer)
{
echo "true";
}

Can I do this with php? What's the actual code?

Posted: Tue Dec 06, 2005 8:39 pm
by neophyte

Code: Select all

function get_browser_name( $user_agent ) {
				$browsers = array( 'Opera' => 'Opera',
								'Mozilla Firefox' => '(Firebird)|(Firefox)',
								'Galeon' => 'Galeon',
								'Mozilla' => 'Gecko',
								'MyIE' => 'MyIE',
								'Lynx' => 'Lynx',
								'Netscape' => '(Mozilla/4\.75)|(Netscape6)|(Mozilla/4\.08)|(Mozilla/4\.5)|(Mozilla/4\.6)|(Mozilla/4\.79)',
								'Konqueror' => 'Konqueror',
								'SearchBot' => '(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)',
								'Internet Explorer 6' => '(MSIE 6\.[0-9]+)',
								'Internet Explorer 5' => '(MSIE 5\.[0-9]+)',
								'Internet Explorer 4' => '(MSIE 4\.[0-9]+)', 
								);
				foreach( $browsers as $browser => $pattern ) {
								if ( eregi( $pattern, $user_agent ) )
												return $browser;
				} 
				return 'Unknown';
}

Enjoy :roll:

Posted: Tue Dec 06, 2005 8:52 pm
by VKX
That's a lot more than I need! I just need that simple code for IE.

Posted: Tue Dec 06, 2005 9:00 pm
by Ambush Commander
It's the PHP Manual to the rescue!

$_SERVER['HTTP_USER_AGENT']
http://us2.php.net/manual/en/function.get-browser.php

Posted: Tue Dec 06, 2005 9:05 pm
by neophyte
Note: In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.
It's been my experience that it's rarely configured... That's why the function.

See:

viewtopic.php?t=33819

I think the end of the thread has a link to the snippet posted above....

Posted: Tue Dec 06, 2005 10:16 pm
by VKX
What does the _SERVER part do?

Posted: Tue Dec 06, 2005 10:29 pm
by neophyte
$_SERVER is an array of global predefined variables. One of them is 'HTTP_USER_AGENT'. It holds info about the person's browser. So refering to the function I posted earlier...

Code: Select all

//Get the browser name
$browser = get_browser_name($_SERVER['HTTP_USER_AGENT']);
//Do a string comparison to see if it's IE
if(stristr('Internet Explorer', $browser)!==false){
//it's ie do something
} else{
//do nothing
}
Untested...