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中显示

相关推荐
奔跑吧邓邓子7 天前
PHPStorm携手ThinkPHP8:开启高效开发之旅
phpstorm·php开发·thinkphp·thinkphp8
centaury3213 天前
使用FastAdmin框架开发二
uniapp·thinkphp·fastadmin
quweiie14 天前
tp8.0\jwt接口安全验证
前端·安全·jwt·thinkphp
未来之窗软件服务1 个月前
thinkphp ThinkPHP3.2.3完全开发手册
thinkphp
quweiie2 个月前
thinkphp8.1 调用巨量广告API接口,刷新token
thinkphp·巨量引擎·巨量广告接口·访问令牌
huohuopro2 个月前
thinkphp模板文件缺失没有报错/thinkphp无法正常访问控制器
后端·thinkphp
汤米粥4 个月前
FastAdmin和thinkPHP学习文档
学习·thinkphp·fastadmin
掘金归海一刀4 个月前
thinkphp6+elementui实现多图片压缩包下载
前端·vue.js·thinkphp
与神明画鸭4 个月前
常见框架漏洞:Thinkphp(TP)篇
漏洞·thinkphp·tp
phper85 个月前
在 Docker 中为 ThinkPHP 项目安装 PHP Redis 扩展并解决 500 错误
redis·docker·php·thinkphp