サーバ変数 のところでブラウザの銘柄が $_SERVER['HTTP_USER_AGENT']
で得られることを勉強しました。
このことを使って,このページをアクセスしたブラウザの銘柄を,SQLite を併用して数えてみましょう(2010-08-01起算)。
| ブラウザ | 回数 |
|---|---|
| Firefox/1 | 3 |
| Firefox/2 | 3 |
| Firefox/3 | 148 |
| Firefox/4 | 55 |
| MSIE 3 | 0 |
| MSIE 4 | 0 |
| MSIE 5 | 1 |
| MSIE 6 | 73 |
| MSIE 7 | 80 |
| MSIE 8 | 204 |
| MSIE 9 | 39 |
| Mozilla/3 | 0 |
| Mozilla/4 | 1 |
| Mozilla/5 | 671 |
| Mozilla/6 | 0 |
| Mozilla/7 | 0 |
| Mozilla/8 | 0 |
| Mozilla/9 | 0 |
| Opera | 27 |
| Other | 457 |
| Safari | 198 |
ソース:
<?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
Last modified: 2010-08-01 22:12:26