PHP code example of ez-php / rate-limiter

1. Go to this page and download the library: Download ez-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/ */

    

ez-php / rate-limiter example snippets


use EzPhp\RateLimiter\ArrayDriver;

$limiter = new ArrayDriver();

if (!$limiter->attempt('login:' . $ip, maxAttempts: 5, decaySeconds: 60)) {
    // Too many attempts — respond with 429
}

$limiter->remainingAttempts('login:' . $ip, 5); // how many hits are still allowed
$limiter->resetAttempts('login:' . $ip);        // clear the counter (e.g. on success)

// Global — in AppServiceProvider::boot()
$app->middleware(new ThrottleMiddleware($limiter, maxAttempts: 60, decaySeconds: 60));

// Per-route
$router->get('/login', [LoginController::class, 'store'])
    ->middleware(new ThrottleMiddleware($limiter, maxAttempts: 5, decaySeconds: 60));

\EzPhp\RateLimiter\RateLimiterServiceProvider::class,


return [
    'driver' => env('RATE_LIMITER_DRIVER', 'array'), // array | redis | cache

    'redis' => [
        'host'     => env('REDIS_HOST', '127.0.0.1'),
        'port'     => (int) env('REDIS_PORT', 6379),
        'database' => (int) env('REDIS_RATE_LIMITER_DB', 0),
    ],
];

interface RateLimiterInterface
{
    public function attempt(string $key, int $maxAttempts, int $decaySeconds): bool;
    public function tooManyAttempts(string $key, int $maxAttempts): bool;
    public function remainingAttempts(string $key, int $maxAttempts): int;
    public function resetAttempts(string $key): void;
}
bash
composer