ThinkPHP5.1 + vue 验证码

it2024-10-17  39

懒得写验证码类,直接用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];

    }

}

注意:

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

use think\facade\Cache;

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

最新回复(0)