简体   繁体   中英

php - Antiflood - how to limit 2 requests per second

I have an anti flood function,

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

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

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

If user requests more than 1 request in 1 second, script stops itself. What I want to do is, I need to allow 2 requests per second maximum (instead of 1). How can I do that ?

I would do it this way:

<?
$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;
}

One thing, though - it will not protect You from DDoS attacks, if You are trying to do this king of thing. Session in PHP can be easily dropped, and even if not, multiple sessions can be created from one client. Read this discussion if You want to know more about protection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM