Reconocer el navegador por PHP


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



Copy this code and paste it in your HTML
  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. if($ua['browser'] === "safari"){
  31. $var = 2;
  32. } elseif($ua['browser'] === "msie"){
  33. $var = 1;
  34. } elseif($ua['browser'] === "firefox"){
  35. $var = 1;
  36. }
  37. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.