<?php
$countFile = __DIR__ . '/num.txt';
$fp = fopen($countFile, 'c+');
if (!$fp) {
die("無法開啟計數器檔案");
}
if (flock($fp, LOCK_EX)) {
$count = (int)fread($fp, 20) + 1;
ftruncate($fp, 0);
rewind($fp);
fwrite($fp, (string)$count);
flock($fp, LOCK_UN);
}
fclose($fp);
echo "您好,您是第 $count 位訪客";
缺點: 頁面執行被計數器 I/O 阻塞;無法用於靜態 HTML;難以快取。
<?php
// counter_js.php
$countFile = __DIR__ . '/num.txt';
$fp = fopen($countFile, 'c+');
if (!$fp) {
echo "document.write('計數器錯誤');";
exit;
}
$count = 0;
if (flock($fp, LOCK_EX)) {
$count = (int)fread($fp, 20) + 1;
ftruncate($fp, 0);
rewind($fp);
fwrite($fp, (string)$count);
flock($fp, LOCK_UN);
}
fclose($fp);
header('Content-Type: application/javascript; charset=UTF-8');
header('Cache-Control: no-cache, must-revalidate');
// 輸出函數呼叫而非 document.write,較安全
echo "window.updateCounter($count);";
<!-- 靜態 HTML -->
<div id="counter">載入中...</div>
<script>
function updateCounter(count) {
document.getElementById('counter').textContent = '訪客數: ' + count.toLocaleString();
}
</script>
<script src="counter_js.php"></script>
<?php
// api/counter.php
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: https://your-site.com'); // 限定來源
header('Cache-Control: no-cache, must-revalidate');
$countFile = __DIR__ . '/../data/counter.txt';
// 簡易速率限制:同 IP 10 秒內僅計數一次
session_start();
$lastCount = $_SESSION['last_count_time'] ?? 0;
if (time() - $lastCount < 10) {
// 仍回傳目前計數,但不遞增
$count = (int)@file_get_contents($countFile);
echo json_encode(['count' => $count, 'incremented' => false]);
exit;
}
$fp = fopen($countFile, 'c+');
if ($fp && flock($fp, LOCK_EX)) {
$count = (int)fread($fp, 20) + 1;
ftruncate($fp, 0);
rewind($fp);
fwrite($fp, (string)$count);
flock($fp, LOCK_UN);
fclose($fp);
$_SESSION['last_count_time'] = time();
echo json_encode(['count' => $count, 'incremented' => true]);
} else {
http_response_code(500);
echo json_encode(['error' => 'Counter unavailable']);
}
<div id="counter" class="counter">
<span class="counter-value">--</span>
<span class="counter-label">訪客</span>
</div>
<script>
(async () => {
const el = document.getElementById('counter');
const valueEl = el.querySelector('.counter-value');
try {
const resp = await fetch('/api/counter.php', {credentials: 'same-origin'});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = await resp.json();
valueEl.textContent = data.count.toLocaleString();
if (data.incremented) {
el.classList.add('just-incremented');
setTimeout(() => el.classList.remove('just-incremented'), 1000);
}
} catch (e) {
console.error('計數器載入失敗:', e);
valueEl.textContent = '?';
el.classList.add('error');
}
})();
</script>
<style>
.counter { display: inline-flex; align-items: center; gap: 0.5rem; font-family: system-ui; }
.counter-value { font-size: 1.5rem; font-weight: 600; transition: transform 0.2s; }
.counter.just-incremented .counter-value { transform: scale(1.2); color: #e67e22; }
.counter.error .counter-value { color: #e74c3c; }
</style>
| 儲存後端 | 優點 | 適用場景 |
|---|---|---|
| Redis INCR | 原子操作、極高效能、支援分布式、可設 TTL 自動過期 | 高流量、多伺服器叢集、即時排行榜 |
| MySQL/PostgreSQL | ACID、持久、易查詢歷史、可關聯業務資料 | 需精確統計、歷史趨勢分析、管理後台 |
| SQLite | 無伺服器、檔案型、支援並發(WAL 模式) | 中小流量、單機部署、不想架資料庫 |
| 檔案 + flock(本文基礎版) | 零依賴、簡單、可攜性高 | 低流量、單機、開發測試、靜態空間 |
<?php
// api/counter_redis.php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$key = 'site:visitor_count';
$count = $redis->incr($key); // 原子遞增
echo json_encode(['count' => $count]);
<?php
// api/counter_db.php
$pdo = new PDO('mysql:host=localhost;dbname=stats;charset=utf8mb4', 'user', 'pass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->beginTransaction();
try {
// 遞增今日計數
$stmt = $pdo->prepare("
INSERT INTO daily_visits (visit_date, count) VALUES (CURDATE(), 1)
ON DUPLICATE KEY UPDATE count = count + 1
");
$stmt->execute();
// 取得總計
$total = $pdo->query("SELECT SUM(count) FROM daily_visits")->fetchColumn();
$today = $pdo->query("SELECT count FROM daily_visits WHERE visit_date = CURDATE()")->fetchColumn();
$pdo->commit();
echo json_encode(['total' => (int)$total, 'today' => (int)$today]);
} catch (Exception $e) {
$pdo->rollBack();
http_response_code(500);
echo json_encode(['error' => 'Database error']);
}
unsafe-inline,符合嚴格 CSP計數器看似簡單,實則包含並發控制、儲存選型、嵌入架構、防刷策略等工程議題。建議採用版本三(獨立 JSON API + Fetch)作為預設方案:關注點分離、非阻塞、易擴充、安全合規。流量增長時,無縫切換至 Redis 或資料庫後端,前端完全不用動。記住:flock() 是檔案計數器的靈魂,沒有它就不是計數器,是亂數產生器。