yggdevsec / rate-limiter
rate-limiter
v1.0.0
2025-07-01 11:59 UTC
Requires
- php: ^8.3 || ^8.4
- ext-memcached: *
- ext-redis: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.75
- phpmd/phpmd: ^2.15
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.5
- vimeo/psalm: ^6.12
README
Support
If you like this project, feel free to support me with a coffee! ☕️
Features
- ✅ PSR-4 autoloading
- ✅ Easy integration with Redis and Memcached storage
- ✅ Validates keys and timestamps to ensure data integrity
Quality Assurance
- ✅ Code analyzed with PHPStan at level 10
- ✅ Code analyzed with PHP psalm
- ✅ Code analyzed with snyk (security scan)
- ✅ Code formatted and cleaned with PHP-CS-Fixer
- ✅ Comprehensive unit tests
Requirements
- PHP 8.3
- Redis extension (
ext-redis
)
Install via:pecl install redis
orapt install php-redis
- Memcached extension (
ext-memcached
)
Install via:pecl install memcached
orapt install php-memcached
- Composer
Example installation on Debian/Ubuntu
sudo apt update
sudo apt install php php-redis php-memcached composer
Initialization
use YggDevSec\Security\RateLimiter\Storage\RedisRateLimitStorage;
use YggDevSec\Security\RateLimiter\Storage\MemcachedRateLimitStorage;
use YggDevSec\Security\RateLimiter\Lock\MemcachedLock;
use YggDevSec\Security\RateLimiter\Lock\RedisLock;
// Create Redis connection
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// Create Memcached connection
$memcached = new Memcached();
$memcached->addServer('127.0.0.1', 11211);
// Inject validators (assume that $keyValidator and $timestampValidator are defined)
$redisStorage = new RedisRateLimitStorage($redis, $keyValidator, $timestampValidator);
$memcachedStorage = new MemcachedRateLimitStorage($memcached, $keyValidator, $timestampValidator);
$lock = new RedisLock($redis);
$lock = new MemcachedLock($memcached);
// Inject validator (assume that $keyValidator defined ) and $lock
$limiter = new RateLimiter(
$redisStorage,
$lock ,
$keyValidator,
3,
60);
Usage Example
$key = $_SERVER['REMOTE_ADDR'] ?? 'unknown-ip';
if ($limiter->tooManyAttempts($key)) {
http_response_code(429);
echo "Too many attempts. Please try again later.";
exit;
}
// Register a new attempt
$limiter->hit($key);
// Proceed with the protected action
echo "Request accepted.";
Testing
To check and fix code style
composer cs
To run static analysis:
composer stan
composer psalm
To run the test suite:
./vendor/bin/phpunit --testdox tests
License
This project is licensed under the MIT License.
YggDevSec
Security-focused PHP libraries
https://gitlab.com/users/yggdevsec/projects