用Redis替代session改写thinkPHP验证码类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kunpeng1987/article/details/80259904

最近有一个项目,因为后端用的是thinkPHP框架,前端用的VueJS框架,需要用到验证码,由于都是用的API,所以原有的tp框架验证码类采用的session存储方式无法实现需求,需要进行改写。记录一下过程,并分享给大家以供参考。
验证码类中主要涉及到两个方法,一个是生成方法entry,另一个就是验证方法check。
1、定一个变量
protected $redis;
在__construct方法中加入redis的连接

$this->redis = new \Redis();
$this->redis->connect(C('REDIS_HOST'), C('REDIS_PORT'));
$this->redis->auth(C('REDIS_AUTH')); //密码验证

2、将entry方法中的这行

session($key.$id, $secode);

改写为redis存储

$this->redis->setex($key . $code, $this->expire, json_encode($secode));

3、将check方法重写

 public function check($code, $id = '')
    {
        $a_code = $this->authcode(strtoupper($code));
        $key = $this->authcode($this->seKey) . $a_code;
        // 验证码不能为空
        $secode = $this->redis->get($key);
        $secode = json_decode($secode, true);
        if (empty($code) || empty($secode)) {
            return false;
        }
        if ($a_code == $secode['verify_code']) {
            $this->reset && $this->redis->delete($key);
            return true;
        }
        return false;
    }

改造完成,最后附上整个源代码类文件。
https://download.csdn.net/download/kunpeng1987/10404049

猜你喜欢

转载自blog.csdn.net/kunpeng1987/article/details/80259904