欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > thinkphp think-captcha 前后端分离 图形验证码

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

2025/6/9 18:00:12 来源:https://blog.csdn.net/fendouweiqian/article/details/145952485  浏览:    关键词:thinkphp think-captcha 前后端分离 图形验证码

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

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等地方。接下来上代码

// 生成验证码,使用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中显示

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词