所以,我有一个超级基本的php api为我的网站,我需要它是率限制。像一个冷却时间,所以ip不能访问api 5分钟。
Thanks in advance =)
有几种方法可以做到这一点,按偏好顺序....
- 使用数据库;有一个记录
ip
和timestamp
的表,然后在每个请求上查找ip
,并检查最后一个请求的时间超过5分钟前 - 使用一个文件以
CSV
或JSON
格式存储请求ip
和timestamp
。然后用每个请求遍历文件…
既然你没有说任何关于访问数据库的事情,下面是JSON
格式文件的版本:
$filePath
变量
$ip = $_SERVER["REMOTE_ADDR"];
$filePath = "./path/to/file.json"; // Set this to a file on your server
$ipList = json_decode(file_get_contents($filePath), true);
$throttleTime = date("Y-m-d H:i:s", strtotime("-5 minutes");
$allowAccess = true;
foreach ($ipList as $key => $row) {
// Check if the IP has accessed the site in the last 5 minutes
if ($row["ip"] === $ip && $row["timestamp"] > $throttleTime)) {
$allowAccess = false;
}
// Remove the entry if over 5 minutes old; not restricted to IP
// >> Garbage colection
if ($row["timestamp"] < $throttleTime) {
unset($ipList[$key]);
}
}
$ipList[] = [
"ip" => $ip,
"timestamp" => date("Y-m-d H:i:s"),
];
// Update the
file_put_contents($filePath, json_encode(array_values($ipList)));
// Check to see if the user is allowed access; exit with error message if not.
if (!$allowAccess) {
echo "Error, you've accessed this site too many times. Try again in 5 minutes.";
exit;
}
// The user is allowed... Do something....
echo "We're in!";