1. Go to this page and download the library: Download kartubi/php-redis-rate 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/ */
kartubi / php-redis-rate example snippets
use Kartubi\RedisRate\Facades\RedisRate;
use Kartubi\RedisRate\Limit;
// Allow 10 requests per second
$result = RedisRate::allow('user:123', Limit::perSecond(10));
if ($result->isAllowed()) {
// Request is allowed
echo "Request allowed. Remaining: " . $result->remaining;
} else {
// Rate limit exceeded
echo "Rate limit exceeded. Retry after: " . $result->getRetryAfterSeconds() . " seconds";
}
use Kartubi\RedisRate\RedisRateLimiter;
use Kartubi\RedisRate\Limit;
class ApiController extends Controller
{
public function __construct(
private RedisRateLimiter $rateLimiter
) {}
public function handle(Request $request)
{
$result = $this->rateLimiter->allow(
'api:' . $request->ip(),
Limit::perMinute(60)
);
if ($result->isExceeded()) {
abort(429, 'Too Many Requests');
}
// Handle the request...
}
}
// 10 requests per second (burst: 10)
$limit = Limit::perSecond(10);
// 60 requests per minute (burst: 60)
$limit = Limit::perMinute(60);
// 1000 requests per hour (burst: 1000)
$limit = Limit::perHour(1000);
// 100 requests per minute with burst capacity of 150
$limit = Limit::custom(
rate: 100, // requests per period
burst: 150, // burst capacity
periodInSeconds: 60 // period in seconds
);
// Allow up to N requests at once
$result = RedisRate::allowN('bulk:user:123', Limit::perSecond(10), 5);
// Allow at most N requests (partial consumption)
$result = RedisRate::allowAtMost('batch:user:123', Limit::perSecond(10), 8);
// Reset all limits for a specific key
RedisRate::reset('user:123');
// In routes/api.php
Route::middleware('redis-rate:api')->group(function () {
Route::get('/users', [UserController::class, 'index']);
});
// With custom limits
Route::middleware('redis-rate:60,api')->get('/search', [SearchController::class, 'search']);
// With custom key
Route::middleware('redis-rate:login,auth:login')->post('/login', [AuthController::class, 'login']);
$result = RedisRate::allow('key', $limit);
// Check if request is allowed
$result->isAllowed(); // true if allowed
$result->isExceeded(); // true if rate limit exceeded
// Get remaining capacity
$result->remaining; // Number of requests remaining
// Get timing information
$result->getRetryAfterSeconds(); // Seconds until next request allowed
$result->getResetAfterSeconds(); // Seconds until rate limit resets
// Get the limit that was applied
$result->limit; // The Limit object used