123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- <?php
- /**
- * RateLimit.php UTF-8
- * 速率限制
- *
- * @date : 2018/10/20 11:34
- *
- * @license 这不是一个自由软件,未经授权不许任何使用和传播。
- * @author : wuyonghong <wyh@huosdk.com>
- * @version : HuoMp 1.0
- */
- namespace huolib\tool;
- use huolib\constant\CacheConst;
- use think\Cache;
- class RateLimit {
- /**
- * @param int $mem_id 玩家ID
- * @param bool $inc_path 是否包含路径
- * @param bool $inc_ip 是否包含IP
- * @param int $limit 限制次数
- * @param int $expire_time 过期时间
- *
- * @return bool
- */
- public function rateLimit($mem_id = 0, $inc_path = true, $inc_ip = true, $limit = 1, $expire_time = 1) {
- $_ip = 0;
- if (true === $inc_ip) {
- $_ip = get_client_ip(1, true);
- }
- $_path = '';
- if (true === $inc_path) {
- $_path = request()->path();
- }
- $_key = CacheConst::CACHE_RATE_LIMIT_PREFIX.$_ip.$mem_id.urlencode($_path);
- $_check = Cache::has($_key);
- if (true == $_check) {
- Cache::inc($_key);
- $_cnt = Cache::get($_key);
- if ($_cnt > $limit) {
- return false;
- }
- } else {
- Cache::set($_key, 1, $expire_time);
- }
- return true;
- }
- }
|