Parsing the User Agent String in PHP
April 8'th 2008 03:00:45 pm
Recently I've been working on the stats logger of the blog and stumbled upon a typical WWW problem. The lack of standars, or more accurately the lack of browsers following standards, this time with the User Agent String.
I googled a bit and couldn't find the thing I was going after, the closest thing I found was this function on dotvoid.com, which is pretty limited to the goal I'm after.
So I decided to create a new user agent parser from the ground up, the goal was to extract as much information as possible as simply as possible, the resulting code consist of 2 functions:
function parse_useragent($agent){ foreach($parts as $key => $value){ switch($key){ case 0: $info = analyze_product_comment($comment); break; case 1: $data['engine'] = $value; break; case 2: $data['engine'] .= " $value"; else $data['browser'] = $value; break; case 3: $data['browser'] = $value; break; case 4: $data['browser'] = $value . " " .$parts[3]; break; } } return $data+$info; } function analyze_product_comment($value){ foreach($parts as $key => $val){ switch($key){ case 0: 'browser' => $parts[1],//Browser 'os' => $parts[2]//OS ); return $info; } $info['platform'] = $val;//Platform break; case 1: $info['security'] = $val;//Security break; case 2: $info['os'] = $val;//OS break; case 3: $info['language'] = $val;//Language break; } } return $info; }
And you just use it by calling the parse_useragent function with the user agent as the first parameter.
Example:
$client = parse_useragent($_SERVER['HTTP_USER_AGENT']); /* Outputs array ( 'product' => 'Mozilla/5.0', 'engine' => 'Gecko/2008032619', 'browser' => 'Firefox/3.0b5', 'platform' => 'Macintosh', 'security' => 'U', 'os' => 'Intel Mac OS X 10.5', 'language' => 'en-US', ) */
Just a friendly reminder. All the code I post in here is licensed under an MIT License unless explicitly stated.