kelunik/rate-limit

为 Amp 提供速率限制

v3.0.0 2023-09-04 17:56 UTC

This package is auto-updated.

Last update: 2024-09-04 20:19:20 UTC


README

License

kelunik/rate-limit 是一个针对 Amp 的速率限制库。

安装

composer require kelunik/rate-limit

用法

当速率限制被超过时,您完全控制任何操作。您也可以在用户超过限制之前提醒用户。

$current = $this->rateLimit->increment("{$userId}:{$action}");

if ($current > $this->limit) {
    // show captcha or error page or do anything you want
} else {
    // request is within the limit, continue normally
}

如果您想公开限制,例如在 HTTP API 中,您也可以请求给定键的复位时间。

$current = $this->rateLimit->increment("{$userId}:{$action}");

$response->setHeader("x-ratelimit-limit", $this->limit);
$response->setHeader("x-ratelimit-remaining", $this->limit - $current);
$response->setHeader("x-ratelimit-reset", $this->rateLimit->getTtl("{$userId}:{$action}"));

RateLimit::getTtl() 返回直到限制重置的秒数。如果您想返回绝对时间,只需将 time() 添加到该值即可。