验证码


生成验证码

namespace app\web\controller;

use Timo\Captcha;
use Timo\Core\Controller;
use Timo\Core\Session;

class passport extends Controller
{
    public function captcha()
    {
        $captcha = new Captcha();
        Session::set('captcha', $captcha->getCode());
        $captcha->getImage();
    }
}

显示验证码

模版页面,比如登录页面

<html>
    <head>
        <meta charset="UTF-8">
        <title>登录</title>
    </head>
    <body>
        <img src="<?= $this->link('passport/captcha'); ?>" />
    </body>
</html>

验证验证码正确性

namespace app\web\controller;

use Timo\Core\App;
use Timo\Core\Controller;
use Timo\Core\Request;
use Timo\Http\Response;
use Timo\Core\Session;

class User extends Controller
{
    /**
     * @method POST
     */
    public function login()
    {
        $code = Request::post('code', '');
                    
        // 验证码错误
        if ($code != Session::get('captcha')) {
            Response::type('json')->send(App::result(1, '验证码错误'));
            return;
        }
        
        //验证码正确,进行登录操作
        
        $this->display();
    }
}

生成base64图片

    如果是前后端分离,我们一般不使用session,那该怎么办呢?这里给了一个解决方案,使用Aes将验证码加密并设置过期时间,如:60s,生成token参数并返回给前端,前端在提交登录请求时带上这个Token
namespace app\web\controller;

use Timo\Captcha;
use Timo\Core\App;
use Timo\Core\Controller;

class passport extends Controller
{
    /**
     * 获取验证码图片
     */
    public function captcha()
    {
        $captcha = new Captcha();
        
        $code = $captcha->getCode();
        $token = AesEncrypt::builder()->expire(60)->encrypt($code);

        return App::result(0, 'ok', [
            'token' => $token,
            'image' => $captcha->getBase64Image(),
        ]);
    }
}