RateLimit.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * RateLimit.php UTF-8
  4. * 速率限制
  5. *
  6. * @date : 2018/10/20 11:34
  7. *
  8. * @license 这不是一个自由软件,未经授权不许任何使用和传播。
  9. * @author : wuyonghong <wyh@huosdk.com>
  10. * @version : HuoMp 1.0
  11. */
  12. namespace huolib\tool;
  13. use huolib\constant\CacheConst;
  14. use think\Cache;
  15. class RateLimit {
  16. /**
  17. * @param int $mem_id 玩家ID
  18. * @param bool $inc_path 是否包含路径
  19. * @param bool $inc_ip 是否包含IP
  20. * @param int $limit 限制次数
  21. * @param int $expire_time 过期时间
  22. *
  23. * @return bool
  24. */
  25. public function rateLimit($mem_id = 0, $inc_path = true, $inc_ip = true, $limit = 1, $expire_time = 1) {
  26. $_ip = 0;
  27. if (true === $inc_ip) {
  28. $_ip = get_client_ip(1, true);
  29. }
  30. $_path = '';
  31. if (true === $inc_path) {
  32. $_path = request()->path();
  33. }
  34. $_key = CacheConst::CACHE_RATE_LIMIT_PREFIX.$_ip.$mem_id.urlencode($_path);
  35. $_check = Cache::has($_key);
  36. if (true == $_check) {
  37. Cache::inc($_key);
  38. $_cnt = Cache::get($_key);
  39. if ($_cnt > $limit) {
  40. return false;
  41. }
  42. } else {
  43. Cache::set($_key, 1, $expire_time);
  44. }
  45. return true;
  46. }
  47. }