2

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 ?

caner taşdemir
  • 203
  • 3
  • 9

1 Answers1

7

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.

Community
  • 1
  • 1
T.Z.
  • 2,092
  • 1
  • 24
  • 39
  • 1
    Not a problem, added additional comment for Your reference. – T.Z. Sep 27 '16 at 10:07
  • note that people actually tying to DoS won't save/reuse sessions, they'll probably create a new session with every request – hanshenrik Sep 27 '16 at 21:27
  • It may not protect you from ddos but it helps reduce the bandwidth use, I have added some code to the second elseif to wait some time before letting the user load content again (which is not possible with the current answer's code). else if($fast_request_check || (isset($_SESSION['wait']) && $_SESSION['wait'] == 'wait')) {$_SESSION['waiting'] = 'wait';if( (time()-30) > $_SESSION['last_session_request']){unset($_SESSION['waiting']);header("location:");} die(); }NOTE: 30 is the waiting time, The header reloads the page because the user has waited the time to be able to load content again – Heriberto Juarez Jun 24 '18 at 05:27