📜  如何在 php 代码示例中获取浏览器信息

📅  最后修改于: 2022-03-11 14:54:29.295000             🧑  作者: Mango

代码示例1
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 = '#(?' . join('|', $known) .')[/ ]+(?[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,
  );
}