核心程式碼
$file = 'count_file.txt';
if (file_exists($file)) {
$count = (int)file_get_contents($file) + 1;
} else {
$count = 1;
}
file_put_contents($file, $count);
echo $count;
進階版:支援多頁面獨立計數
function page_counter(string $pageId): int {
$dir = __DIR__ . '/counters/';
if (!is_dir($dir)) mkdir($dir, 0755, true);
$file = $dir . md5($pageId) . '.txt';
$count = file_exists($file) ? (int)file_get_contents($file) : 0;
$count++;
file_put_contents($file, $count, LOCK_EX);
return $count;
}
// 使用
echo '本頁瀏覽次數: ' . page_counter($_SERVER['REQUEST_URI']);
效能與擴展建議
- 高流量場景請改用 Redis
INCR 或 MySQL 原子更新
- 加入 Cookie/Session 去重,避免刷新重複計數
- 定期將檔案計數同步至資料庫做持久化分析
- 使用
LOCK_EX 防止併發寫入資料損壞