php 限制访问次数
- 限制访问次数的php 文件
- 提示 : 会生成一个 visits.json 文件 用来记录访问日志 并不是恶意文件
- 需要指定正确的访问路径
<?php
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$content_path = "./index.html";
$maxVisits = 5;
$visitTimeFrame = 10;
$filePath = './visits.json';
if (!file_exists($filePath)) {file_put_contents($filePath, json_encode([]));
}$visits = json_decode(file_get_contents($filePath), true);
foreach ($visits as $ipKey => $visitData) {if (time() - $visitData['lastVisit'] > $visitTimeFrame) {unset($visits[$ipKey]);}
}$null404 = '<html><head><title>404 Not Found</title></head><body><center><h1>404 Not Found</h1></center><hr><center>nginx</center></body></html>';
$content = file_get_contents($content_path);
if (isset($visits[$ip])) {if ($visits[$ip]['count'] >= $maxVisits && strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false) {echo $null404; } else {$visits[$ip]['count']++;$visits[$ip]['lastVisit'] = time();echo $content;}
} else {$visits[$ip] = ['count' => 1, 'lastVisit' => time()];echo $content;
}
file_put_contents($filePath, json_encode($visits));?>