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

相关推荐
用户14644605033793 天前
PHP 多维数组处理利器:array_column() 用法详解
php·thinkphp
用户3074596982078 天前
ThinkPHP 6.0 多应用模式下的中间件机制详解
后端·thinkphp
行思理18 天前
小游戏系统提供二开服务
layui·游戏程序·小游戏·thinkphp
xmode1 个月前
常用自定义函数laravel版+thinkphp版
后端·php·laravel·thinkphp
mooyuan天天1 个月前
内网渗透之Thinkphp5提权实战+reGeorg代理横向移动(CVE-2018-20062)
内网渗透·横向移动·thinkphp·regeorg·cve-2018-20062·thinkphp代码执行漏洞
蹦极的考拉1 个月前
夜间无法登录:ThinkPHP api接口 23:00 准时罢工的排查全纪录
小程序·thinkphp·api接口·无法登陆
青茶3602 个月前
ThinkCMF是一个开源的内容管理框架
php·cms·thinkphp
quweiie2 个月前
thinkphp8.0链接SQL SERVER2022数据库
数据库·sqlserver·thinkphp
ghie90902 个月前
基于ThinkPHP实现动态ZIP压缩包的生成
thinkphp
用户3074596982072 个月前
容器(Container)—— 对象的“智能工厂+调度官”
后端·thinkphp