Php Browser Detection Class


/ Published in: PHP
Save to your folder(s)

Detect and echo browser version including differentiating between Chrome and Safari.


Copy this code and paste it in your HTML
  1. <?php
  2. class Browser
  3. {
  4. private $props = array("Version" => "0.0.0",
  5. "Name" => "unknown",
  6. "Agent" => "unknown") ;
  7.  
  8. public function __Construct()
  9. {
  10. $browsers = array("firefox", "msie", "opera", "chrome", "safari",
  11. "mozilla", "seamonkey", "konqueror", "netscape",
  12. "gecko", "navigator", "mosaic", "lynx", "amaya",
  13. "omniweb", "avant", "camino", "flock", "aol");
  14.  
  15. $this->Agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  16. foreach($browsers as $browser)
  17. {
  18. if (preg_match("#($browser)[/ ]?([0-9.]*)#", $this->Agent, $match))
  19. {
  20. $this->Name = $match[1] ;
  21. $this->Version = $match[2] ;
  22. break ;
  23. }
  24. }
  25. }
  26.  
  27. public function __Get($name)
  28. {
  29. if (!array_key_exists($name, $this->props))
  30. {
  31. die ("No such property or function $name") ;
  32. }
  33. return $this->props[$name] ;
  34. }
  35.  
  36. public function __Set($name, $val)
  37. {
  38. if (!array_key_exists($name, $this->props))
  39. {
  40. SimpleError("No such property or function.", "Failed to set $name", $this->props) ;
  41. die ;
  42. }
  43. $this->props[$name] = $val ;
  44. }
  45.  
  46. }
  47. $Browser = new Browser;
  48. ?>
  49.  
  50. <?php //usage
  51. echo "$Browser->Name $Browser->Version" ;
  52. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.