todo: 图片验证码的原理

发布于 2024-11-13 19:17:01

图片验证码的原理
一、生成图片的过程:

<img src="{:captcha_src()}" width="100" height="40" onclick="this.src = '{:captcha_src()}?r=' + Math.random();"/>

这里的captcha_src() 就是调用的C:08fastadmin1.2.0.20201008_fullvendortopthinkthink-captchasrchelper.php
里的captcha_src()
这个函数返回/captcha.html ,img src 请求/captcha.html。这个路径会调用C:08fastadmin1.2.0.20201008_fullvendortopthinkthink-captchasrchelper.php的

function captcha($id = '', $config = [])
{
  $captcha = new \think\captcha\Captcha($config);
  return $captcha->entry($id);
}

$captcha->entry这就是会返回img 内容

public function entry($id = '')
{
  ......
  ob_start();
  // 输出图像
  imagepng($this->im);
  $content = ob_get_clean();
  imagedestroy($this->im);
  return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
}

二、校验的过程:
1、调用
$captchaResult = \think\Validate::is($captcha, 'captcha');

2、
C:08fastadmin1.2.0.20201008_fullvendortopthinkthink-captchasrchelper.php

function captcha_check($value, $id = '')
{
  $captcha = new \think\captcha\Captcha((array)\think\Config::get('captcha'));
  return $captcha->check($value, $id);
}

3、C:08fastadmin1.2.0.20201008_fullvendortopthinkthink-captchasrcCaptcha.php
这里可以看出,是要从session里取$secode['verify_code']进行比较

public function check($code, $id = '')
{
    $key = $this->authcode($this->seKey) . $id;
    $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;
}

那是什么时候放进session的呢
在这个函数里先生成图片,然后将code放到到session

public function entry($id = '')
{
  ......
  // 保存验证码
  $key = $this->authcode($this->seKey);
  $secode                = [];
  $secode['verify_code'] = $code; // 把校验码保存到session
  $secode['verify_time'] = time(); // 验证码创建时间
  Session::set($key . $id, $secode, '');
  ......
}
0 条评论

发布
问题