PHP code example of alphavel / rate-limit

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

    

alphavel / rate-limit example snippets


// routes/api.php

// 100 requests per minute per IP
$router->middleware('rate_limit:100,60,ip')->group(function ($router) {
    $router->post('/auth/login', [AuthController::class, 'login']);
});

// 1000 requests per minute per authenticated user
$router->middleware(['auth', 'rate_limit:1000,60,user'])->group(function ($router) {
    $router->get('/users', [UserController::class, 'index']);
});

// 10 requests per minute per IP on this specific endpoint
$router->middleware('rate_limit:10,60,endpoint')->post('/heavy-operation', [Controller::class, 'heavy']);

$router->middleware([
    'rate_limit:1000,60,ip',      // 1000/min per IP
    'rate_limit:100,60,user',      // 100/min per user
    'rate_limit:10,60,endpoint'    // 10/min on this endpoint
])->post('/ai/generate', [AIController::class, 'generate']);

// config/rate_limit.php

'whitelist' => [
    '127.0.0.1',
    '::1',
    '10.0.0.0/8',        // Private network
    '192.168.1.100',     // Load balancer
],

// config/rate_limit.php

'swoole' => [
    'max_entries' => 100000, // Adjust based on unique IPs/users expected
],

// bootstrap/server.php

use Alphavel\RateLimit\Drivers\SwooleTableDriver;

// Initialize BEFORE server start
SwooleTableDriver::init(config('rate_limit.swoole.max_entries', 100000));

$server->start();
bash
php alpha vendor:publish --tag=rate-limit-config
bash
php alpha rate-limit:stats
bash
php alpha rate-limit:list

# Show only blocked entries
php alpha rate-limit:list --blocked
bash
php alpha rate-limit:reset ip:192.168.1.1
bash
# Block for 1 hour (default)
php alpha rate-limit:block ip:192.168.1.1

# Block for specific duration
php alpha rate-limit:block ip:192.168.1.1 --duration=3600