我想知道我如何限制我的php api,所以ip或客户端不能使用它5分钟



所以,我有一个超级基本的php api为我的网站,我需要它是率限制。像一个冷却时间,所以ip不能访问api 5分钟。

Thanks in advance =)

有几种方法可以做到这一点,按偏好顺序....

  1. 使用数据库;有一个记录iptimestamp的表,然后在每个请求上查找ip,并检查最后一个请求的时间超过5分钟前
  2. 使用一个文件以CSVJSON格式存储请求iptimestamp。然后用每个请求遍历文件…

既然你没有说任何关于访问数据库的事情,下面是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!";

最新更新