ブラウザの統計

[TODO] 新しいブラウザに対応させる必要があります。特にChromeはSafariと誤認されます。

例1

サーバ変数 のところでブラウザの銘柄が $_SERVER['HTTP_USER_AGENT'] で得られることを勉強しました。

このことを使って,このページをアクセスしたブラウザの銘柄を,SQLite を併用して数えてみましょう(2010-08-01起算)。

ブラウザ回数
Firefox/1230
Firefox/2257
Firefox/3298
Firefox/4364
MSIE 30
MSIE 40
MSIE 53
MSIE 6170
MSIE 73052
MSIE 8368
MSIE 92937
Mozilla/30
Mozilla/424
Mozilla/53946
Mozilla/60
Mozilla/70
Mozilla/80
Mozilla/90
Opera60
Other1607
Safari3043

ソース:

<?php
  try {
    $u = $_SERVER['HTTP_USER_AGENT'];
    if (preg_match("/MSIE \d/", $u, $matches))
      $x = $matches[0];
    elseif (preg_match("/Firefox\/\d/", $u, $matches))
      $x = $matches[0];
    elseif (preg_match("/Safari/", $u, $matches))
      $x = $matches[0];
    elseif (preg_match("/Opera/", $u, $matches))
      $x = $matches[0];
    elseif (preg_match("/Mozilla\/\d/", $u, $matches))
      $x = $matches[0];
    else
      $x = "Other";
    $db = new PDO('sqlite:ファイル名');
    $sql = "update httpua set cnt = cnt + 1 where browser = '$x'";
    $result = $db->exec($sql)
      or die("<p>テーブルが更新できません</p>");
    $sql = "select * from httpua order by browser";
    echo "<table border=\"1\">\n";
    echo "<tr><th>ブラウザ</th><th>回数</th></tr>\n";
    foreach ($db->query($sql) as $entry)
      echo "<tr><td>", $entry['browser'], "</td><td>", $entry['cnt'], "</td></tr>\n";
    echo "</table>\n";
    $db = null;
  } catch (PDOException $e) {
    echo "<p>エラー:", $e->getMessage(), "</p>";
  }
?>

あらかじめサーバにログインして,例えば次のように打ち込んでおきます:

sqlite3 ファイル名
create table httpua(browser text, cnt int);
insert into httpua values('MSIE 9', 0);
insert into httpua values('MSIE 8', 0);
insert into httpua values('MSIE 7', 0);
insert into httpua values('MSIE 6', 0);
insert into httpua values('MSIE 5', 0);
insert into httpua values('MSIE 4', 0);
insert into httpua values('MSIE 3', 0);
insert into httpua values('Firefox/1', 0);
insert into httpua values('Firefox/2', 0);
insert into httpua values('Firefox/3', 0);
insert into httpua values('Firefox/4', 0);
insert into httpua values('Safari', 0);
insert into httpua values('Opera', 0);
insert into httpua values('Mozilla/9', 0);
insert into httpua values('Mozilla/8', 0);
insert into httpua values('Mozilla/7', 0);
insert into httpua values('Mozilla/6', 0);
insert into httpua values('Mozilla/5', 0);
insert into httpua values('Mozilla/4', 0);
insert into httpua values('Mozilla/3', 0);
insert into httpua values('Other', 0);
.quit