Home > Dev > PHP Security > Rate Limiting

Rate Limiting

This code implements rate limiting to prevent brute force attacks.

function rate_limit($identifier) {
    $max_requests = 100; // Maximum number of requests
    $time_window = 3600; // Time window in seconds

    $current_time = time();
    $ip = $_SERVER['REMOTE_ADDR'];
    $request_key = "$identifier:$ip";

    if (apcu_exists($request_key)) {
        $request_count = apcu_fetch($request_key);
        if ($request_count >= $max_requests) {
            header('HTTP/1.1 429 Too Many Requests');
            exit('Too Many Requests');
        } else {
            apcu_inc($request_key);
        }
    } else {
        apcu_add($request_key, 1, $time_window);
    }
}

// Usage example
rate_limit('login');
Back