PHP code example of anjola / php_rate_limiter

1. Go to this page and download the library: Download anjola/php_rate_limiter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

anjola / php_rate_limiter example snippets


use PHPRateLimiter\RateLimiter;

$maxAttempts = 5;      // Maximum allowed attempts
$decaySeconds = 60;    // Time window in seconds

$rateLimiter = new RateLimiter($maxAttempts, $decaySeconds);

$key = 'user_ip_or_identifier';

if ($rateLimiter->tooManyAttempts($key)) {
    // Handle rate limit exceeded (e.g., block request, show error)
} else {
    // Proceed with the request
}

$rateLimiter->clearRecords($key);

use PHPRateLimiter\Analytics;

$prefix = 'myapp_';  // Optional prefix for event keys
$analytics = new Analytics($prefix);

$event = 'homepage_visit';
$count = $analytics->trackEvent($event);
echo "Event count: " . $count;

$count = $analytics->getEventCount($event);

$analytics->resetEvent($event);



use PHPRateLimiter\RateLimiter;

$rateLimiter = new RateLimiter(10, 60); // 10 attempts per 60 seconds
$key = $_SERVER['REMOTE_ADDR'];

if ($rateLimiter->tooManyAttempts($key)) {
    header('HTTP/1.1 429 Too Many Requests');
    echo "You have exceeded the maximum number of requests. Please try again later.";
    exit;
}

// Proceed with your application logic here



use PHPRateLimiter\Analytics;

$analytics = new Analytics('app_');
$analytics->trackEvent('user_signup');

echo "User signup count: " . $analytics->getEventCount('user_signup');
bash
composer