thinkphp: 用redis存储短信验证码(thinkphp v6.0.12LTS)

发布时间 2023-04-16 22:14:42作者: 刘宏缔的架构森林

一,配置redis

1,编辑.env

[REDIS0]
TYPE = redis
HOST = 127.0.0.1
PORT = 6379
PASSWORD =

2,config/cache.php

<?php

// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------

return [
    // 默认缓存驱动
    'default' => env('cache.driver', 'file'),

    // 缓存连接方式配置
    'stores'  => [
        'file' => [
            // 驱动方式
            'type'       => 'File',
            // 缓存保存目录
            'path'       => '',
            // 缓存前缀
            'prefix'     => '',
            // 缓存有效期 0表示永久缓存
            'expire'     => 0,
            // 缓存标签前缀
            'tag_prefix' => 'tag:',
            // 序列化机制 例如 ['serialize', 'unserialize']
            'serialize'  => [],
        ],
        // 更多的缓存连接
        'redis0'    =>    [
            'type'     => env('redis0.type', 'redis'),
            'host'     => env('redis0.host', '127.0.0.1'),
            'port'     => env('redis0.port', '6379'),
            'password' => env('redis0.password', ''),
            'select'   => '0',
            // 全局缓存有效期(0为永久有效)
            'expire'   => 0,
            // 缓存前缀
            'prefix'   => '',
            'timeout'  => 0,
        ],
    ],
];

说明:短信验证码的发送频率控制,参见这一篇:

https://www.cnblogs.com/architectforest/p/17323844.html

二,php代码:

1,app/lib/AuthCodeUtil.php

<?php
namespace app\lib\util;


//短信验证码存储到redis
class AuthCodeUtil {
    //redis连接
    private $cache;
    //验证码的保存秒数,600秒,即:10分钟
    private $ttl = 600;

    //构造
    public function __construct($cache){
        $this->cache = $cache;
    }

    //生成code保存到redis,并返回code
    public function setCode($mobile) {
        $key = "Auth:".$mobile;
        $code = $this->newAuthCode();
        $this->cache->set($key,$code,$this->ttl);
        return $code;
    }

    //校对验证码
    public function verifyCode($mobile,$code) {
        $key = "Auth:".$mobile;
        $cacheCode = $this->cache->get($key);
        //var_dump($cacheCode);
        if ($cacheCode == $code) {
            return true;
        } else {
            return false;
        }
    }

    //生成一个验证码
    public function newAuthCode(){
        $code = rand(100000,999999);
        return $code;
    }
}

2,controller中调用:

class Sms extends BaseController
{
    private $cache;//cache的连接

    public function __construct(App $app = null){
         //继承父类的构造方法
         parent::__construct($app);
        $this->cache = Cache::store('redis0');
    }

    //发送验证码
    public function send() {
          $mobile = $this->request->param('mobile','','string');
          //检查发送频率,返回是否可发送
          $rate = new SmsRateUtil($this->redis);
          $ret = $rate->setRate($mobile);
           $res = "";
          if ($ret == '1') {    //可发送
             //生成code并保存到redis
             $auth = new AuthCodeUtil($this->cache);
             $code = $auth->setCode($mobile);
             //发送短信代码,需调用短信服务商的sdk

             //返回
             $data = ['msg'=>'短信已发送'];
             return Result::Success($data);
          } else if ($ret == '0') {
             $res = "请超过60秒之后再发短信";
          } else if ($ret == '2') {
             $res = "当前手机号本日内发送数量已超限制";
          } else {
             $res = "发生错误";
          }
          return Result::ErrorCode(10024,$res);
    }


    //检查验证码是否正确
    public function verify(){
        $mobile = $this->request->param('mobile','','string');
        $code = $this->request->param('code','','string');
        //验证
        $auth = new AuthCodeUtil($this->cache);
        $ret = $auth->verifyCode($mobile,$code);
        if ($ret == true){
           echo "验证码正确";
        }  else {
           echo "验证码错误";
        }
    }

三,测试效果

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

四,查看thinkphp的版本:

liuhongdi@lhdpc:/data/php/imgtouch$ php think version
v6.0.12LTS