頁面總訪問 300 次,超限跳轉他頁。需統計**全站總訪問量**而非單 IP。
<?php
$counterFile = 'counter.txt';
$limit = 300;
$redirectUrl = 'https://example.com/limit.html';
if (!file_exists($counterFile)) {
file_put_contents($counterFile, '0');
}
$count = (int)file_get_contents($counterFile);
if ($count >= $limit) {
header("Location: $redirectUrl");
exit;
}
$count++;
file_put_contents($counterFile, (string)$count);
echo "剩餘訪問次數: " . ($limit - $count);
?>
$fp = fopen($counterFile, 'c+');
flock($fp, LOCK_EX);
$count = (int)fread($fp, filesize($counterFile));
if ($count < $limit) {
$count++;
ftruncate($fp, 0);
fwrite($fp, (string)$count);
} else {
// 超限
}
flock($fp, LOCK_UN);
fclose($fp);
INCR 原子計數,高效支援高併發。counter:{ip},並設定過期時間。