yggdevsec/rate-limiter
最新稳定版本:v1.1.0
Composer 安装命令:
composer require yggdevsec/rate-limiter
包简介
rate-limiter
README 文档
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 formatted and cleaned with PHP-CS-Fixer
- ✅ Comprehensive unit tests
Requirements
- PHP 8.3
- Redis extension (
ext-redis)
Install via:pecl install redisorapt install php-redis - Memcached extension (
ext-memcached)
Install via:pecl install memcachedorapt 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 is 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
统计信息
- 总下载量: 4
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-01