Simple Browser Detection

  |   By  |  0 Comments

I wanted a simple and fast PHP browser detector for a script recently. Most scripts are either very out of date or huge and look for every single browser possible.  Here’s a simple one that will return the major ones.

function browser_detect(){
//simple major browser detection
//returns an array 0=>browser name and version,1=>browser name, 2=>Version no
$props    = array("Version" => "0.0.0", "Name" => "unknown", "Agent" => "unknown") ;
$browsers = array("firefox", "msie", "opera", "chrome", "safari", "mozilla", "seamonkey","konqueror", "netscape", "gecko", "navigator", "mosaic", "lynx", "amaya",                            "omniweb", "avant", "camino", "flock", "aol");
foreach($browsers as $browser) 
            if (preg_match("#($browser)[/ ]?([0-9.]*)#", $user_agent, $match)) 
                if ($match[1]=='msie')$match[1]='Internet Explorer';
                $match[2]=round($match[2],1);//just major version
              return $match;   
return $props;//no match        

The trick was putting Chrome fairly near the start of the $browsers array or it gets missed!
Call browser_detect() which returns an array where
0=>Browser Name and version
1=>Browser Name