Search code examples
phpjquerycaptchaweb-traffic

Show captcha when unexpected navigation detected to prevent traffic abuse


I noticed that some user overloading my website by downloading multiple files (for example 500 files at same time) and opening more pages in small duration, I want to show captcha if unexpected navigation detected by user.

I know how to implement Captcha, but I can't figure out what is the best approach to detect traffic abuse using (PHP)?


Solution

  • A common approach is to use something like memcached to store the requests on a minute basis, I have open sourced a small class that achieves this: php-ratelimiter

    If you are interested in a more thorough explanation of why the requests need to be stored on a minute basis, check this post.

    So to sum it up, your code could end up looking like this:

    if (!verifyCaptcha()) {
        $rateLimiter = new RateLimiter(new Memcache(), $_SERVER["REMOTE_ADDR"]);
        try {
            $rateLimiter->limitRequestsInMinutes(100, 5);
        } catch (RateExceededException $e) {
            displayCaptcha();
            exit;
        }
    }
    

    Actually, the code is based on a per-minute basis but you can quite easily adapt this to be on a per 30 seconds basis:

    private function getKeys($halfminutes) {
        $keys = array();
        $now = time();
        for ($time = $now - $halfminutes * 30; $time <= $now; $time += 30) {
            $keys[] = $this->prefix . date("dHis", $time);
        }
        return $keys;
    }