验证码

 


 

生成验证码

namespace app\web\controller;

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

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

 

显示验证码

模版页面,比如登录页面

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

 

验证验证码正确性

namespace app\web\controller;

use Timo\Core\Controller;
use Timo\Core\Request;

class User extends Controller
{
    public function login()
    {
        if (Request::isPost()) {
            $code = Request::post('code', '');
            
            // 验证码错误
            if ($code != Session::get('captcha')) {
                Response::type('json');
                return array(
                    'code' => 4001,
                    'msg' => '验证码错误'
                );
            }
            
            //验证码正确,进行登录操作
            
        }
        
        $this->display();
    }
}