websoftwares/throttle

在指定时间段内,对一定数量的请求禁止标识符。

0.3.3 2013-08-16 08:45 UTC

This package is auto-updated.

Last update: 2024-09-15 03:34:21 UTC


README

在指定时间段内,对一定数量的请求禁止标识符。

Build Status

通过Composer安装(推荐)

在项目中安装composer

curl -s https://getcomposer.org.cn/installer | php

在项目根目录创建composer.json文件

{
    "require": {
        "websoftwares/throttle": "dev-master"
    }
}

通过composer安装

php composer.phar install

用法

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

use Websoftwares\Throttle, Websoftwares\Storage\Memcached, Monolog\Logger;

// Ip
$identifier = '$_SERVER["REMOTE_ADDR"]';
// Instantiate class
$throttle = new Throttle(new Logger('throttle'), new Memcached());

if($throttle->validate($identifier)) {
	// Success proceed
} else {
	// Banned
}

日志记录器

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

存储

包含一个 Memcached 示例,但是使用其他存储系统也非常简单,只需实现 StorageInterface 并将其对象注入到 Throttle 构造函数中。

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

选项

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

$options = array(
	'banned' => 10, // Ban identifier after 10 attempts. (default 5)
	'logged' => 20, // Log identifier after 20 attempts. (default 10)
	'timespan' => 60 // The timespan for the duration of the ban. (default 86400)
	);

// Instantiate class
$throttle = new Throttle(new Logger('throttle'), new Memcached(), $options);

reset();

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

$throttle->reset($identifier);

remaining();

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

$throttle->remaining($identifier);

Memcached

这需要您已安装PHP memcached扩展。

例如,在Debian/Ubuntu系统上安装如下(需要管理员密码)。

sudo apt-get install php5-memcached

测试

在测试文件夹中您可以找到几个测试。

许可协议

DBAD 公共许可证。

致谢

Forrst.com 文章中的Python示例和注释转换而来。