CaptchaCache.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Cache;
  3. use App\Libs\Utils;
  4. use Illuminate\Support\Facades\Redis;
  5. class CaptchaCache
  6. {
  7. /**
  8. * 写入验证码答案
  9. *
  10. * @param string $key
  11. * @param string $code
  12. * @param int $ttl 有效期(秒)
  13. * @return void
  14. */
  15. public static function set(string $key, string $code, int $ttl)
  16. {
  17. $cacheKey = Utils::getCacheKey('captcha.code', [$key]);
  18. Redis::setex($cacheKey, $ttl, strtolower($code));
  19. }
  20. /**
  21. * 取出并立即删除验证码答案(一次性消费,防止同一答案被重复使用)
  22. *
  23. * @param string $key
  24. * @return string 不存在或已过期时返回空字符串
  25. */
  26. public static function pull(string $key): string
  27. {
  28. if ($key === '') {
  29. return '';
  30. }
  31. $cacheKey = Utils::getCacheKey('captcha.code', [$key]);
  32. $code = (string)Redis::get($cacheKey);
  33. if ($code !== '') {
  34. Redis::del($cacheKey);
  35. }
  36. return $code;
  37. }
  38. }