sideShow_bob/throttle

在一定时间段内,禁止某个标识符超过一定数量的请求。

0.4.3 2016-02-17 10:04 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:53:01 UTC


README

在一定时间段内,禁止某个标识符超过一定数量的请求。

Build Status

安装

建议的安装方法是使用 composer

php composer.phar require "sideshow_bob/throttle"

用法

Throttle 类禁止标识符的基本用法。

// ip
$identifier = $_SERVER["REMOTE_ADDR"];
// instantiate class
$throttle = new \sideshow_bob\Throttle(new \sideshow_bob\Storage\Memcached());

if($throttle->validate($identifier)) {
    // success proceed
} else {
    // banned
}

存储

包括 ArrayMemcachedRedisPredisdoctrine/cache 存储实现,但使用其他存储系统也很容易,只需实现 StorageInterface 并将其对象注入到 Throttle 构造函数中即可。

####注意#### 无论您决定使用哪种存储系统,都不要将失败的请求数据存储到您的数据库中,这可能导致DDoS攻击并使数据库崩溃。

选项

您可以通过实例化一个 Throttle 类并将一个 数组 作为第三个参数传递来覆盖默认选项。

$options = [
    "ban" => 10,      // ban identifier after 10 attempts. (default 5)
    "log" => 20,      // log identifier after 20 attempts. (default 10)
    "timespan" => 60, // the timespan for the duration of the ban. (default 86400)
];

// Instantiate class
$throttle = new \sideshow_bob\Throttle(new \sideshow_bob\Storage\Memcached(), $options);

日志记录器

任何实现 PSR-3 LoggerInterface 的日志记录库都应工作,只需创建您的日志记录器对象并将其注入到 Throttle 构造函数中。例如,出色的日志记录库 Monolog

其他方法

reset()

这将从存储中删除标识符。

$throttle->reset($identifier);

remaining()

这将返回一个整数,表示在标识符被禁止之前可用的尝试次数。

$throttle->remaining($identifier);

测试

测试文件夹包含所有测试。

致谢

websoftwares/throttle 分支。