| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- <?php
- namespace App\Cache;
- use App\Libs\Utils;
- use Illuminate\Support\Facades\Redis;
- class CaptchaCache
- {
- /**
- * 写入验证码答案
- *
- * @param string $key
- * @param string $code
- * @param int $ttl 有效期(秒)
- * @return void
- */
- public static function set(string $key, string $code, int $ttl)
- {
- $cacheKey = Utils::getCacheKey('captcha.code', [$key]);
- Redis::setex($cacheKey, $ttl, strtolower($code));
- }
- /**
- * 取出并立即删除验证码答案(一次性消费,防止同一答案被重复使用)
- *
- * @param string $key
- * @return string 不存在或已过期时返回空字符串
- */
- public static function pull(string $key): string
- {
- if ($key === '') {
- return '';
- }
- $cacheKey = Utils::getCacheKey('captcha.code', [$key]);
- $code = (string)Redis::get($cacheKey);
- if ($code !== '') {
- Redis::del($cacheKey);
- }
- return $code;
- }
- }
|