Limitrr PHP 在很大程度上受到了我为 NodeJS 创建的另一个库 Limitrr 的启发。点击这里查看。
Limitrr PHP 允许用户轻松地在应用中集成速率限制。与其他类似的包不同,该工具不仅允许用户按请求数量进行限制,还可以按已完成操作的数量进行限制(例如允许在一个时间段内成功创建一定数量的账户),并可配合自定义选项对其进行限制。此外,它还支持自定义标识符——你不再需要仅根据用户 IP 进行限制。
该库还提供了一个中间件函数,可让你轻松地对 SlimPHP 项目中可能存在的各种路由进行限流。
如果你喜欢这个项目,请在 GitHub 上为它点亮 🌟。
欢迎提交 Pull Request
你可以通过在终端中执行以下命令行来安装 limitrr-php 库(假设你已经安装了 Composer):
composer require eddiejibson/limitrr-php "^1.0"
require "/vendor/autoload.php"; //Require composer's autoload
$options = [
//Redis keystore information
"redis" => [
"host" => "666.chae.sh",
"port" => 6379,
"password" => "supersecret",
],
"routes" => [
"default" => [
"requestsPerExpiry" => 5,
],
],
];
//Initialize the Limitrr class and pass the options defined above into it
//Note that the options are not required.
$limitrr = new \eddiejibson\limitrr\Limitrr($options);
//Various examples like this can be found further into the documentation,
//for each function.
$result = $limitrr->get(["discriminator" => $ip]);
echo $result["requests"] + " Requests";
echo $result["completed"] + " Completed";
//Note that this library is no means just for SlimPHP, it just happens to
//provide a middleware function for those who may need it.
//Usage within SlimPHP
$app = new Slim\App();
//Use the Limitrr SlimPHP middleware function, if you wish:
$app->add(new \eddiejibson\limitrr\RateLimitMiddleware($limitrr)); //Make sure to pass in the main Limitrr
//instance we defined above into the middleware function. This is mandatory.
//You can also add the get IP middleware function, it will append the user's real IP
//(behind Cloudflare or not) to the request.
$app->add(new \eddiejibson\limitrr\getIpMiddleware());
//Example usage within a route
$app->get("/hello/{name}", function ($request, $response, $args) {
$name = $args["name"];
$ip = $request->getAttribute('realip'); //Get the IP that was defined within Limitrr's get IP middleware function
return $response->getBody()->write("Hello, ${name}. Your IP is ${ip}.");
});
//You do not have to app the middleware function to every single route, globally.
//You can do it indivually, too - along with passing options into such. Like so:
$app->get("/createUser/{name}", function ($request, $response, $args) {
//Non intensive actions like simple verification will have a different limit to intensive ones.
//and will only be measured in terms of each request via the middleware.
//No further action is required.
if (strlen($args["name"]) < 5) {
//Dummy function creating user
$res = $someRandomClass->registerUser();
if ($res) {
//Intensive actions like actually registering a user should have a
//different limit to normal requests, hence the completedActionsPerExpiry option.
//and should only be added to once this task has been completed fully
//In this example, we will be limiting the amount of completed actions a certain IP can make.
//Anything can be passed in here, however. For example, a email address or user ID.
//$request->getAttribute('realip') was determined by calling the middleware earlier - getIpMiddleware()
$limitrr->complete(["discriminator"] => $ip);
}
}
})->add(new \eddiejibson\limitrr\RateLimitMiddleware($limitrr, ["route"=>"createUser"]));
//You can also pass the route name within the limitrr middleware function
$app->run();
返回: 数组
$limitrr->get([
"discriminator" => $discriminator, //Required
"route" => $route, //Not required, default is assumed
"type" => $type //Not required
]);
必须通过数组传递给函数
default 路由获取计数requests 或 completed,此时仅返回对应的整数值$limitrr->get([
"discriminator" => $discriminator,
"type" => $type,
"route" => $route
]); //Besides discriminator, all parameters are optional.
//If type is not passed into the function, it will
//return both the amount of requests and completed actions
//Where discriminator is the thing being limited
//e.g x amount of completed actions/requests per discriminator
$limitrr->get(["discriminator" => $discriminator]);
//This tends to be the user's IP.
$limitrr->get(["discriminator" => $ip]);
//This will return both the amount of requests and completed actions stored under the
//discriminator provided in an object. You can handle like this:
$result = $limitrr->get(["discriminator" => $ip]);
echo $result["requests"] + " Requests";
echo $result["completed"] + " Completed";
//The above example would get the request and completed task count from the default
//route. If you would like to retrieve values from a different route, you can specify
//this as well. It can be done like this:
$result = $limitrr->get(["discriminator" => $ip, "route" => "exampleRouteName"]);
echo $result["requests"] . " Requests made through the route exampleRouteName";
echo $result["completed"] . " Completed Tasks made through the route exampleRouteName";
//You may also only fetch only one type of value - instead of both requests and completed.
$result = $limitrr->get(["discriminator" => $ip, "route" => "exampleRouteName", "type" => "completed"]);
echo $result["completed"] . " Completed tasks made through the route exampleRouteName";
返回: 整数
$limitrr->get([
"discriminator" => $discriminator, //Required
"route" => $route, //Not required, default is assumed
]);
必须通过数组传递给函数
default 路由获取计数返回: 布尔值
$limitrr->reset([
"discriminator" => $discriminator, //Required
"route" => $route, //Not required, default is assumed,
"type" => $type //Not required
]);
必须通过数组传递给函数
default 路由重置计数requests 还是 completed?如果未设置,则两者都会被移除//Where discriminator is the thing being limited
//e.g x amount of completed actions/requests per discriminator
//This will remove both the amount of requests and completed action count
$limitrr->reset(["discriminator" => $discriminator]);
//This tends to be the user's IP.
$limitrr->reset(["discriminator" => $ip]);
//If you wish to reset counts from a particular route, this can be done as well.
//As the type is not specified, it will remove both the request and completed count
$result = $limitrr->reset([
"discriminator" => $ip,
"route" => "exampleRouteName"
]);
if ($result) {
echo "Requests removed from the route exampleRouteName";
} else {
//Do something else
}
//If you want to remove either one of the amount of requests or completed actions.
//but not the other, this can be done as well.
//The value passed in can either be "requests" or "completed".
//In this example, we will be removing the request count for a certain IP
$result = $limitrr->reset([
"discriminator" => $ip,
"type" => "requests"
]);
if ($result) {
echo "Request count for the specified IP were removed"
} else {
//do something else
}
必填: 否
类型: 数组或字符串
描述: Redis 连接信息。
既可以传入包含 Redis 实例 URI 的字符串,也可以传入包含连接信息的对象:
6379"127.0.0.1"""0 //Pass in a string containing a redis URI.
"redis" => "redis://127.0.0.1:6379/0"
//Alternatively, use an array with the connection information.
"redis" => [
"port" => 6379, //Redis Port. Required: false. Defaults to 6379
"host" => "127.0.0.1", //Redis hostname. required: False. Defaults to "127.0.0.1".
"password" => "mysecretpassword1234", //Redis password. Required: false. Defaults to null.
"database" => 0 //Redis database. Required: false. Defaults to 0.
]
必填: 否
类型: 数组
描述: 与 Limitrr 相关的各种选项。
"limitrr"429(Too Many Requests,请求过多)"options" => [
"keyName" => "myApp", //The keyname all of the requests will be stored under. Required: false. Defaults to "limitrr"
"errorStatusCode" => 429 //Should important errors such as failure to connect to the Redis keystore be caught and displayed?
]
必填:否
类型:数组
描述:定义路由限制。
在 routes 对象内部,你可以定义许多独立的路由,并为其设置自定义规则。可设置的自定义规则如下:
100requestsPerExpiry 中的值;如果未设置则为 5900(15 分钟)expiry 中的值;如果未设置则为 900(15 分钟)requests 和 actions。当用户被限流时,将向用户返回此消息。如果 requests 中未设置字符串,则默认为 "As you have made too many requests, you are being rate limited."。此外,如果 completed 中未设置值,则将使用 中的字符串;如果两者都未设置,则其值为 "routes" => [
//Overwrite default route rules - not all of the keys must be set,
//only the ones you wish to overwrite
"default" => [
"expiry": 1000
],
"exampleRoute" => [
"requestsPerExpiry" => 100,
"completedActionsPerExpiry" => 5,
"expiry" => 900,
"completedExpiry" => 900,
"errorMsgs" => [
"requests" => "As you have made too many requests, you are being rate limited.",
"completed" => "As you performed too many successful actions, you have been rate limited."
]
],
//If not all keys are set, they will revert to
//the default values
"exampleRoute2" => [
"requestsPerExpiry" => 500
]
]
requests"As you performed too many successful actions, you have been rate limited."