yggdevsec/rate-limiter

rate-limiter

v1.0.0 2025-07-01 11:59 UTC

This package is auto-updated.

Last update: 2025-07-01 10:24:37 UTC


README

Support

If you like this project, feel free to support me with a coffee! ☕️

Buy Me 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

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