我正在使用以下内容限制IP每5分钟发送1条消息。 所以我想回应剩下的时间,我该如何计算呢?
这是我的PHP
$query = "SELECT * FROM messages WHERE ip = '$ip' AND mtime >= NOW() - INTERVAL 5 MINUTE";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
echo "<script>
alert ('You can only send 5 message every 10min. please wait.')
</script>";
} else {
}
答案 0 :(得分:3)
如果你的mtime列包含microtime值,你可以这样做:
$query = "SELECT * FROM messages WHERE ip = '$ip' AND mtime >= NOW() - INTERVAL 5 MINUTE ORDER by mtime DESC";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$diff = microtime(true) - $row['mtime']; //here the time difference between last sended message and this try
$remaining = (5*60 - (int) $diff);
...
}
else {
...
}
我还更改了查询顺序,以便区分现在和最后一条消息。如果您以后需要每次检查5封邮件,则需要删除该订单。
如果microtime不工作,您可以使用时间功能:
$diff = time() - $row['mtime'];
答案 1 :(得分:0)
在时间戳中首先得到当前时间
$c_time = strtotime(date('d-M-Y g:i:s'));
现在得到的时间超过5分钟
$l_time = $c_time-(5*60);
现在提出您的查询
$query = "SELECT * FROM messages WHERE ip = '$ip' AND mtime >= '$l_time' ORDER by mtime DESC";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$remaining_time = $c_time - $row['mtime']; // this will be remaining time in seconds use it accordingly
...
}
else {
...
}
我希望你能找到答案