PHP code example of aporat / laravel-rate-limiter

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

    

aporat / laravel-rate-limiter example snippets


// config/database.php
'redis' => [
    'client' => env('REDIS_CLIENT', 'phpredis'),
    // ...
    'rate-limiter' => [
        'url' => env('REDIS_URL'),
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'port' => env('REDIS_PORT', '6379'),
        'password' => env('REDIS_PASSWORD'),
        'database' => env('RATE_LIMITER_REDIS_DB', '2'),
        'timeout' => 0.5,
        'read_timeout' => 0.5,
    ],
],

Route::middleware('rate.limiter')->group(...);                        // windows and key from config
Route::middleware('rate.limiter:60,1')->group(...);                   // 60 per 1 minute, like `throttle`
Route::middleware('rate.limiter:minute=60,hourly=1000')->group(...);  // explicit windows
Route::middleware('rate.limiter:minute=30,key=user,name=api')->group(...);
Route::middleware('rate.limiter:minute=5,key=ip+route')->post('/login', ...);

use Aporat\RateLimiter\Middleware\RateLimit;

Route::middleware(RateLimit::with(minute: 60, hourly: 1000, key: ['user', 'route'], name: 'api'));
// 'rate.limiter:minute=60,hourly=1000,key=user+route,name=api'

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\Aporat\RateLimiter\Middleware\RateLimit::class);
})

use Aporat\RateLimiter\Facades\RateLimiter;
use Aporat\RateLimiter\Exceptions\RateLimitException;

// 5 submissions per hour per user; throws RateLimitException (rendered as 429)
RateLimiter::create($request)
    ->withUserId($request->user()->id)
    ->withName('form_submission')
    ->withTimeInterval(3600)
    ->limit(5);

// Check without throwing
$result = RateLimiter::withName('export')->withUserId($userId)->withTimeInterval(60)->attempt(2);
if (! $result->allowed) {
    return back()->withErrors("Try again in {$result->retryAfter()}s");
}

// Count unconditionally (e.g. duplicate detection)
$count = RateLimiter::create($request)->withRequestInfo()->withUserId($userId)->withTimeInterval(10)->record();

// Copy headers onto a response
RateLimiter::create($request)->withClientIpAddress()->withResponse($response)->limit(100);

// Several windows at once, atomically
RateLimiter::attempt(['user', (string) $userId], [60 => 10, 3600 => 100]);

RateLimiter::blockIpAddress('203.0.113.7');        // block_seconds (default 24h)
RateLimiter::blockIpAddress('203.0.113.7', 600);
RateLimiter::unblockIpAddress('203.0.113.7');
RateLimiter::isIpAddressBlocked('203.0.113.7');    // bool
RateLimiter::blockedFor('203.0.113.7');            // seconds left