[TODO] 新しいブラウザに対応させる必要があります。特にChromeはSafariと誤認されます。
サーバ変数 のところでブラウザの銘柄が $_SERVER['HTTP_USER_AGENT']
で得られることを勉強しました。
このことを使って,このページをアクセスしたブラウザの銘柄を,SQLite を併用して数えてみましょう(2010-08-01起算)。
| ブラウザ | 回数 |
|---|---|
| Firefox/1 | 233 |
| Firefox/2 | 257 |
| Firefox/3 | 299 |
| Firefox/4 | 364 |
| MSIE 3 | 0 |
| MSIE 4 | 0 |
| MSIE 5 | 3 |
| MSIE 6 | 170 |
| MSIE 7 | 3053 |
| MSIE 8 | 368 |
| MSIE 9 | 2937 |
| Mozilla/3 | 0 |
| Mozilla/4 | 24 |
| Mozilla/5 | 4099 |
| Mozilla/6 | 0 |
| Mozilla/7 | 0 |
| Mozilla/8 | 0 |
| Mozilla/9 | 0 |
| Opera | 60 |
| Other | 1621 |
| Safari | 3210 |
ソース:
<?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