首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

PHP 限制 IP 訪問次數:文件計數器實現超限跳轉

     編輯:程式設計疑難解答

需求

頁面總訪問 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);
?>

併發安全版 (flock)

$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);

生產環境建議

  • 使用 Redis INCR 原子計數,高效支援高併發。
  • 若需**單 IP 限制**,鍵改為 counter:{ip},並設定過期時間。
  • 文件鎖在高併發下性能差,僅適合低流量頁面。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved