Advertisement
Guest User

Untitled

a guest
Sep 11th, 2012
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.16 KB | None | 0 0
  1. <?php
  2.  
  3.     /* Once in 10 seconds, 5 times per minute, 10 times per 5 minutes. */
  4.     $rate_limits = array(10 => 1, 60 => 5, 300 => 10);
  5.     $max_interval = max(array_keys($rate_limits)); /* 300 */
  6.  
  7.     /*
  8.       For example:
  9.  
  10.       SELECT attempt_time FROM account_access_attempts
  11.       WHERE account_id = ...
  12.         AND attempt_time < NOW() - 300 seconds
  13.       ORDER BY attempt_time DESC
  14.  
  15.       Or do a ZRANGE query to Redis, or whatever.
  16.  
  17.       Make sure access times are ordered, otherwise things will break.
  18.     */
  19.     # $attempt_times = get_account_access_times($username);
  20.    $attempt_times = array(time() - 1, time() - 9, time() - 15);
  21.  
  22.     list($delay, $now, $count, $interval, $limit) = array(0, time(), 0, 0, 0);
  23.  
  24.     reset($rate_limits);
  25.     foreach ($attempt_times as $ts) {
  26.         $count++;
  27.  
  28.         if ($interval === 0 || $now - $ts > $interval) {
  29.             list($interval, $limit) = each($rate_limits);
  30.             if (!isset($interval)) { break; } # Safety measure
  31.        }
  32.  
  33.         if ($count >= $limit) { $delay = max($delay, $interval - ($now - $ts)); }
  34.     }
  35.     unset($now, $count, $interval, $limit);
  36.  
  37.     echo $delay;
  38.  
  39. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement