php前后端登陆验证,基于 ThinkPHP 前后端分离, 验证码的使用

本文介绍了在ThinkPHP框架下,结合Vue2.0实现前后端分离登录时的验证码处理方法。代码示例展示了如何生成并保存验证码到session,以及在高并发情况下使用session_create_id()生成唯一标识来防止冲突。同时,文章提及了验证码的验证过程,并提出了将验证码存储在Redis以解决Session局限性的建议。
摘要由CSDN通过智能技术生成

ThinkPHP + Vue 2.0 前后端分离, 登录遇到验证码问题,如何保证一一对应, 记录下

验证码生成类, 用的是框架自带的生成类 文档地址 , 用法按照文档上的操作就可以, 上代码

/**

* 输出验证码并把验证码的值保存的session中

* 验证码保存到session的格式为: array('verify_code' => '验证码值', 'verify_time' => '验证码创建时间');

* @access public

* @param string $id 要生成验证码的标识

* @return \think\Response

*/

public function entry($id = '')

{

// 图片宽(px)

$this->imageW || $this->imageW = $this->length * $this->fontSize * 1.5 + $this->length * $this->fontSize / 2;

// 图片高(px)

$this->imageH || $this->imageH = $this->fontSize * 2.5;

// 建立一幅 $this->imageW x $this->imageH 的图像

$this->im = imagecreate($this->imageW, $this->imageH);

// 设置背景

imagecolorallocate($this->im, $this->bg[0], $this->bg[1], $this->bg[2]);

// 验证码字体随机颜色

$this->color = imagecolorallocate($this->im, mt_rand(1, 150), mt_rand(1, 150), mt_rand(1, 150));

// 验证码使用随机字体, 我把类从vendor 目录下, 提取出来了, 所以路径需要更换

$ttfPath = ROOT_PATH . '/vendor/topthink/think-captcha/assets/' . ($this->useZh ? 'zhttfs' : 'ttfs') . '/';

if (empty($this->fontttf)) {

$dir = dir($ttfPath);

$ttfs = [];

while (false !== ($file = $dir->read())) {

if ('.' != $file[0] && substr($file, -4) == '.ttf') {

$ttfs[] = $file;

}

}

$dir->close();

$this->fontttf = $ttfs[array_rand($ttfs)];

}

$this->fontttf = $ttfPath . $this->fontttf;

if ($this->useImgBg) {

$this->background();

}

if ($this->useNoise) {

// 绘杂点

$this->writeNoise();

}

if ($this->useCurve) {

// 绘干扰线

$this->writeCurve();

}

// 绘验证码

$code = []; // 验证码

$codeNX = 0; // 验证码第N个字符的左边距

if ($this->useZh) {

// 中文验证码

for ($i = 0; $i < $this->length; $i++) {

$code[$i] = iconv_substr($this->zhSet, floor(mt_rand(0, mb_strlen($this->zhSet, 'utf-8') - 1)), 1, 'utf-8');

imagettftext($this->im, $this->fontSize, mt_rand(-40, 40), $this->fontSize * ($i + 1) * 1.5, $this->fontSize + mt_rand(10, 20), $this->color, $this->fontttf, $code[$i]);

}

} else {

for ($i = 0; $i < $this->length; $i++) {

$code[$i] = $this->codeSet[mt_rand(0, strlen($this->codeSet) - 1)];

$codeNX += mt_rand($this->fontSize * 1.2, $this->fontSize * 1.6);

imagettftext($this->im, $this->fontSize, mt_rand(-40, 40), $codeNX, $this->fontSize * 1.6, $this->color, $this->fontttf, $code[$i]);

}

}

// 保存验证码

$key = $this->authcode($this->seKey);

$code = $this->authcode(strtoupper(implode('', $code)));

$secode = [];

$secode['verify_code'] = $code; // 把校验码保存到session

$secode['verify_time'] = time(); // 验证码创建时间

Session::set($key . $id, $secode, '');

ob_start();

// 输出图像

imagepng($this->im);

$content = ob_get_clean();

imagedestroy($this->im);

return response($content, 200, ['Content-Length' => strlen($content), 'Uuid' => $key . $id])->contentType('image/png');

}

改动过程中, 需要修改 vendor 下的源文件, 预防其他人整体 composer install 之后, 源码 又改回去, 所以将代码放在了 vendor 目录外, 当做一个三方类使用. 只改动了两个地方其他

1. // 验证码使用随机字体, 我把类从vendor 目录下, 提取出来了, 所以路径需要更换, 确保字体文件可以找到

$ttfPath = ROOT_PATH . '/vendor/topthink/think-captcha/assets/' . ($this->useZh ? 'zhttfs' : 'ttfs') . '/';

2. // 将验证码唯一标识, 放在 header 头里, 返回给前端

return response($content, 200, ['Content-Length' => strlen($content), 'Uuid' => $key . $id])->contentType('image/png');

}

使用, 生成验证码

public function index()

{

$config = [

// 验证码字体大小

'fontSize' => 80,

// 验证码位数

'length' => 4,

// 关闭验证码杂点

'useNoise' => true,

];

$id = session_create_id(); // 生成一个随机 id 确保唯一

$captcha = new NewCaptcha($config);

return $captcha->entry($id);

}

PHP uniqid()函数可用于生成不重复的唯一标识符,该函数基于微秒级当前时间戳。在高并发或者间隔时长极短(如循环代码)的情况下,会出现大量重复数据。即使使用了第二个参数,也会重复。

使用session_create_id()函数生成唯一标识符,php session_create_id()是php 7.1新增的函数,用来生成session id,低版本无法使用。

校验

前端从验证码的 header 头里取出 uuid 参数, 登录的时候一起传递到后台, 进行校验

$uuid = $params['uuid'];

$captchaClass = new NewCaptcha();

if(!$captchaClass->check($captcha, $uuid)) {

jsonBack([1006, '验证码错误!']);

}

// 新的 check 方法, 和原来的比少了一个拼接参数的操作

/**

* 验证验证码是否正确

* @access public

* @param string $code 用户验证码

* @param string $key 验证码标识

* @return bool 用户验证码是否正确

*/

public function check($code, $key = '')

{

// 验证码不能为空

$secode = Session::get($key, '');

if (empty($code) || empty($secode)) {

return false;

}

// session 过期

if (time() - $secode['verify_time'] > $this->expire) {

Session::delete($key, '');

return false;

}

if ($this->authcode(strtoupper($code)) == $secode['verify_code']) {

$this->reset && Session::delete($key, '');

return true;

}

return false;

}

Tips: 生成的验证码, 放在 Session 中 有一定的局限性, 可以放在 Redis 中 , 有不对的地方, 欢迎指出.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值