只需将 IP 和请求时间存储在日志文件中。然后检查每个请求的日志文件是否存在该 IP 并比较存储的时间。
这是一个简单的脚本,它只允许 10 秒后来自同一 IP 的请求:
$waitSeconds = 10;
if (allowRequest($waitSeconds)) {
// allowed
echo "Welcome.";
} else {
// not allowed
echo "Please wait at least $waitSeconds after your last request.";
}
echo '<hr /><a href="#" onclick="location.reload(true);return false">try again</a>';
function getLastRequestTimeDiff($ip = null, $logFile = null)
{
if ($ip === null) {
// no specific ip provided, grab vom $_SERVER array
$ip = $_SERVER["REMOTE_ADDR"];
}
if ($logFile === null) {
// no specific log file taken
$logFile = "./lookup.log";
}
if (!is_file($logFile)) {
// touch
file_put_contents($logFile, serialize(array()));
}
// read content
$logContent = file_get_contents($logFile);
// unserialize, check manual
$lookup = unserialize($logContent);
// default diff (f.e. for first request)
$diff = 0;
// current timestamp
$now = time();
if (array_key_exists($ip, $lookup)) {
// we know the ip, retrieve the timestamp and calculate the diff
$diff = $now - $lookup[$ip];
}
// set the new request time
$lookup[$ip] = $now;
// serialize the content
$logContent = serialize($lookup);
// and write it back to our log file
file_put_contents($logFile, $logContent);
// return diff (in seconds)
return $diff;
}
// encapsulate our function in a more simple function (allow yes/no)
function allowRequest($allowed = 10, $ip = null, $logFile = null)
{
$timeDiff = getLastRequestTimeDiff($ip, $logFile);
return $timeDiff >= $allowed;
}