Sooner or later it might become necessary to write an application that tracks site visitor browser types. Here’s some code to use:

<?php
echo($_SERVER[‘HTTP_USER_AGENT’]);
?>

This will output something that looks like one of the following:

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) 
Mozilla/4.0 (compatible; MSIE 5.0; Mac_PowerPC)
Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0

Reference
A more complete list of USER AGENT strings (tab delimited)

Next, we’ll build a simple browser checker to check for Internet Explorer (IE), Firefox, Opera and Safari:

<?php
$useragent = $_SERVER[‘HTTP_USER_AGENT’]);

if (preg_match(‘|MSIE ([0-9].[0-9]{1,2})|’,$useragent,$matched)) {
    $browser_version=$matched[1];
    $browser = ‘IE’;
} elseif (preg_match( ‘|Opera ([0-9].[0-9]{1,2})|’,$useragent,$matched)) {
    $browser_version=$matched[1];
    $browser = ‘Opera’;
} elseif(preg_match(‘|Firefox/([0-9\.]+)|’,$useragent,$matched)) {
        $browser_version=$matched[1];
        $browser = ‘Firefox’;
} elseif(preg_match(‘|Safari/([0-9\.]+)|’,$useragent,$matched)) {
        $browser_version=$matched[1];
        $browser = ‘Safari’;
} else {
        // browser not recognized!
    $browser_version = 0;
    $browser= ‘other’;
}

print “browser: $browser $browser_version”;
?>

Now let’s parse out a simple Operating System (OS) checker using the strstr function:

<?php
$useragent = $_SERVER[‘HTTP_USER_AGENT’]);

if (strstr($useragent,‘Win’)) {
    $os=‘Win’;
} else if (strstr($useragent,‘Mac’)) {
    $os=‘Mac’;
} else if (strstr($useragent,‘Linux’)) {
    $os=‘Linux’;
} else if (strstr($useragent,‘Unix’)) {
    $os=‘Unix’;
} else {
    $os=‘Other’;
}

print “OS: <b>$os”;
?>