php - Antiflood - 如何限制每秒2个请求

时间:2016-09-27 08:51:50

标签: php

我有防洪功能,

if (!isset($_SESSION)) {
    session_start();
}

if($_SESSION['last_session_request'] > time() - 1){
die();
}

$_SESSION['last_session_request'] = time();

如果用户在1秒内请求超过1个请求,脚本将自行停止。我想要做的是,我需要允许每秒最多2个请求(而不是1)。 我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

我会这样做:

<?
$time_interval = 1;#In seconds
$max_requests = 2;
$fast_request_check = ($_SESSION['last_session_request'] > time() - $time_interval);

if (!isset($_SESSION)) 
{
    # This is fresh session, initialize session and its variables
    session_start();
    $_SESSION['last_session_request'] = time();
    $_SESSION['request_cnt'] = 1;
}
elseif($fast_request_check && ($_SESSION['request_cnt'] < $max_requests))
{
   # This is fast, consecutive request, but meets max requests limit
   $_SESSION['request_cnt']++;
}
elseif($fast_request_check)
{
    # This is fast, consecutive request, and exceeds max requests limit - kill it
    die();
}
else
{
    # This request is not fast, so reset session variables
    $_SESSION['last_session_request'] = time();
    $_SESSION['request_cnt'] = 1;
}
但有一件事 - 如果你试图做这件事的话,它不会保护你免受DDoS攻击。可以轻松删除PHP中的会话,即使没有,也可以从一个客户端创建多个会话。 Read this discussion如果您想了解有关保护的更多信息。