thinkphp think-captcha 前后端分离 图形验证码

think-captcha 本身支持API 接口的形式返回,可以看到源代码:

php 复制代码
ob_start();
// 输出图像
imagepng($this->im);
$content = ob_get_clean();
imagedestroy($this->im);

// API调用模式
if ($this->api) {
    return [
        'code' => implode('', $text),
        'img'  => 'data:image/png;base64,' . base64_encode($content),
    ];
}
// 输出验证码图片
return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');

但是官方没有说明,也未提供方法验证。

我们自己实现,逻辑很简单:code就是验证码,img是base64的图形,直接给前端用

我们只需要将验证码存储到redis、file等地方。接下来上代码

php 复制代码
// 生成验证码,使用key、value保存
public function captcha()
{
    $captcha = Captcha::create();

    $token = uniqid('captcha_', true);
    Cache::store('redis')->set($token, $captcha['code'], 300);

    return $this->data([
        'vcode' => $token,
        'image' => $captcha['img'],
    ]);
}

// 校验验证码
public function account()
{
   $captcha = Request::param('captcha');
    $vcode = Request::param('vcode');

    // 从 Redis 获取验证码
    $code = Cache::store('redis')->get($vcode);
    if (!$code || strtolower($code) !== strtolower($captcha)) {
        return $this->faiL('验证码错误');
    }
    Cache::store('redis')->delete($vcode);

    ... 其他的业务逻辑
}

前端代码就不写了,接口调用,获取到vcode和image

将vcode返回、image放到图片src中显示

相关推荐
ETO_冬3 天前
ThinkPHP使用phpword读取模板word文件并添加表格
服务器·word·php·thinkphp
ETO_冬12 天前
FastAdmin后端列表导入表格数据
javascript·thinkphp·fastadmin
ETO_冬21 天前
Fastadmin根据链接参数显示不同列表格
javascript·php·thinkphp·fastadmin
新知图书1 个月前
ThinkPHP 8 操作JSON数据
php·thinkphp
新知图书1 个月前
ThinkPHP 8模型与数据的插入、更新、删除
php·thinkphp
新知图书1 个月前
ThinkPHP 8的多对多关联
php·thinkphp
新知图书2 个月前
ThinkPHP 8的一对一关联
php·thinkphp
新知图书2 个月前
PHP与ThinkPHP连接数据库示例
开发语言·数据库·php·thinkphp
胡萝卜的兔2 个月前
thinnkphp5.1和 thinkphp6以及nginx,apache 解决跨域问题
运维·nginx·apache·thinkphp