Posted By

danwhite85 on 10/29/10


Tagged

php browser


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ddavidd


PHP browser detection light


 / Published in: PHP
 

  1. <?php
  2.  
  3. function browser_info($agent=null) {
  4. // Declare known browsers to look for
  5. $known = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape',
  6. 'konqueror', 'gecko');
  7.  
  8. // Clean up agent and build regex that matches phrases for known browsers
  9. // (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor
  10. // version numbers. E.g. "2.0.0.6" is parsed as simply "2.0"
  11. $agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']);
  12. $pattern = '#(?<browser>' . join('|', $known) .
  13. ')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';
  14.  
  15. // Find all phrases (or return empty array if none found)
  16. if (!preg_match_all($pattern, $agent, $matches)) return array();
  17.  
  18. // Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase,
  19. // Opera 7,8 have a MSIE phrase), use the last one found (the right-most one
  20. // in the UA). That's usually the most correct.
  21. $i = count($matches['browser'])-1;
  22. return array($matches['browser'][$i] => $matches['version'][$i],
  23. 'browser' => $matches['browser'][$i],
  24. 'version' => $matches['version'][$i]);
  25. }
  26. //get browser info
  27. $ua = browser_info();
  28.  
  29. //show what's returned
  30. echo '<pre>';
  31. echo print_r( $ua );
  32. echo '</pre>';
  33.  
  34. /*
  35. // Various browser tests you can do with the returned array ...
  36. if ($ua['firefox']) ... // true
  37. if ($ua['firefox'] > 3) ... // true
  38. if ($ua['firefox'] > 4) ... // false
  39. if ($ua['browser'] == 'firefox') ... // true
  40. if ($ua['version'] > 3.5) ... // true
  41. if ($ua['msie']) ... // false ('msie' key not defined)
  42. if ($ua['opera'] > 3) ... // false ('opera' key not defined)
  43. if ($ua['safari'] < 3) ... // false also ('safari' key not defined)
  44. */

Report this snippet  

You need to login to post a comment.