ThinkPHP5.1 + vue 验证码

懒得写验证码类,直接用ThinkPHP的

composer require topthink/think-captcha=2.0.*

找到vendor/topthink/think-captcha/src/Captcha.php  function entry

line:198

1

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

修改为以下代码:

1

$code = md5(strtoupper(implode(''$code)));

 

line:203

1

2

3

4

5

6

7

8

9

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)])->contentType('image/png');

修改为以下代码

1

2

3

4

5

6

7

8

9

10

$randomKey $this::randomCode();

Cache::set($randomKey$secode, 3600);

 

ob_start();

// 输出图像

imagepng($this->im);

$content = ob_get_clean();

imagedestroy($this->im);

 

return ['content' => "data:image/png;base64," base64_encode($content), 'key' => $randomKey];

Captcha.php新增function randomCode:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/**

 * 生成随机码

 * @access private

 * @author super

 * @time 2020-08-12

 * @return string

 * */

private function randomCode()

{

    $randomCode = md5(time() . rand(1000, 9999) . rand(10, 99));

    if (Cache::get($randomCode)) {

        $this->randomCode();

    }

    return $randomCode;

}

验证:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

/**

 * 验证

 * @access private

 * @author super

 * @time 2020-08-12

 * @param string $code 用户输入的验证码

 * @param string $key 验证码key(生成验证码时返回)

 * @return array

 * */

private function checkCode($code$key)

{

    $data = Cache::pull($key);

    if (!isset($data['verify_time']) || !isset($data['verify_code']))   return ['code' => 501, 'msg' => '验证码已过期'];

    if (time() > $data['verify_time'] + 1800)   return ['code' => 501, 'msg' => '验证码已过期'];

 

    $code = md5(strtoupper($code));

    if ($code != $data['verify_code']) {

        return ['code' => 501, 'msg' => '验证码错误'];

    else {

        return ['code' => 200];

    }

}

注意:

  1. 需修改代码行数可能与上文标注不一致,以实际代码为准

  2. use think\facade\Cache;

  3. 文件保存失败问题,请检查服务器文件夹www权限是否可写

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值