設計思路
- 用單個文本文件 (
counter.dat) 存儲所有頁面計數,格式:頁面URL|計數| 每行一條。
- 以
$_SERVER['REQUEST_URI'] 區分不同頁面。
- 讀取全文件 → 內存數組處理 → 一次性寫回,減少 I/O。
- 封裝為函數/文件,用
require 復用。
核心代碼 (counter.inc.php)
<?php
function showCounter(string $counterFile = 'counter.dat'): int {
$uri = $_SERVER['REQUEST_URI'] ?? '/';
$sign = false;
$data = file_exists($counterFile) ? file($counterFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
foreach ($data as &$line) {
[$page, $count] = explode('|', $line, 2) + ['', '0'];
if ($page === $uri) {
$count++;
$line = "$page|$count|";
$sign = true;
echo $count;
break;
}
}
if (!$sign) {
$count = 1;
$data[] = "$uri|$count|";
echo $count;
}
// 原子寫入 (臨時文件 + rename)
$tmp = $counterFile . '.tmp';
file_put_contents($tmp, implode("\n", $data) . "\n");
rename($tmp, $counterFile);
return $count;
}
?>
頁面中調用
<?php require 'counter.inc.php'; ?>
<!DOCTYPE html>
<html><body>
<p>本頁瀏覽次數: <?php showCounter(); ?> </p>
</body></html>
改進方向
- 高併發:文件鎖
flock() 或改用 **Redis INCR** (incr("page:{$uri}"))。
- 統計維度:區分 PV/UV (用 Cookie/Session 標識唯一訪客)。
- 排除爬蟲:檢查
User-Agent 關鍵字、IP 名單。
- 持久化:定時同步到 MySQL 做歷史分析。