Skip to content

How to get browser info in PHP?

function get_agent_info() {
  $u_agent = $_SERVER['HTTP_USER_AGENT'];
  $temp = strtolower($_SERVER['HTTP_USER_AGENT']);

  $bname    = 'Unknown';
  $platform = 'Unknown';
  $version  = "";

  // Get the platform
  if (preg_match('/linux/i', $temp)) {
    $platform = 'linux';
  }
  elseif (preg_match('/macintosh|mac os x/i', $temp)) {
    $platform = 'mac';
  }
  elseif (preg_match('/windows|win32/i', $temp)) {
    $platform = 'windows';
  }

  // Get the name of the useragent
  if(preg_match('/msie/i',$temp) && !preg_match('/opera/i',$temp)) {
    $bname = 'Internet Explorer';
    $ub = "msie";
  }
  elseif(preg_match('/firefox/i',$temp)) {
    $bname = 'Mozilla Firefox';
    $ub = "firefox";
  }
  elseif(preg_match('/chrome/i',$temp)) {
    $bname = 'Google Chrome';
    $ub = "chrome";
  }
  elseif(preg_match('/safari/i',$temp)) {
    $bname = 'Apple Safari';
    $ub = "safari";
  }
  elseif(preg_match('/opera/i',$temp)) {
    $bname = 'Opera';
    $ub = "opera";
  }
  elseif(preg_match('/netscape/i',$temp)) {
    $bname = 'Netscape';
    $ub = "netscape";
  }

  $known = array('version', $ub, 'other');
  $pattern = '#(?<browser>' . join('|', $known) .')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
  preg_match_all($pattern, $temp, $matches);

  $i = count($matches['browser']);
  if ($i != 1) {
    if (strripos($temp,"version") < strripos($temp,$ub)) {
      $version = $matches['version'][0];
    }
    else {
      $version = $matches['version'][1];
    }
  }
  else {
    $version = $matches['version'][0];
  }

  if ($version == null || $version == "") {
    $version = "?";
  }

  return array(
    'userAgent' 	=> $u_agent,
    'browser'      	=> $bname,
    'version'   	=> $version,
    'platform' 		=> $platform,
  );
}
See also  Python code snippet - How to append two numpy arrays?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.