RateLimiter
The RateLimiter class provides a lightweight mechanism to throttle incoming requests. It utilizes APCu (Alternative PHP Cache) to store counters in shared memory, ensuring near-zero latency overhead.
System Requirements
APCu Extension Required
This class relies on the apcu PHP extension. If not enabled, the application will throw an Internal Server Error (500).
- Open your
php.inifile. - Search for
;extension=apcu. - Remove the semicolon (
;) to uncomment it. - Restart Apache.
- Go to Select PHP Version.
- Click on the Extensions tab.
- Find and check the box for apcu.
API Reference
static check(string $key, int $maxAttempts = 60, int $seconds = 60): void
Checks if the given key has exceeded the limit. If valid, it increments the counter. If exceeded, it terminates the request immediately.
Parameters:
$key: Unique identifier (e.g., User IP, User ID, API Token).$maxAttempts: Number of allowed requests within the window.$seconds: Duration of the time window.
Boom::tooManyRequests (HTTP 429) response and exits.
Usage Examples
1. Throttling by IP Address
Limit a user IP to 60 requests per minute. Useful for general API protection.
<?php
use PP\Security\RateLimiter;
use PP\Request;
// Identify user by IP address
$userIp = Request::$remoteAddr;
// Allow 60 requests per 60 seconds
RateLimiter::check($userIp, 60, 60);
// ... Continue with application logic ...
?>
2. Protecting Login Endpoints
Stricter limits for sensitive actions. Allow only 5 login attempts every 2 minutes.
<?php
use PP\Security\RateLimiter;
use PP\Request;
// Use a specific key prefix to separate this limit from others
$key = 'login_attempt:' . Request::$remoteAddr;
// Allow 5 attempts per 120 seconds
RateLimiter::check($key, 5, 120);
// ... Process Login ...
?>