验证码


生成验证码

  1. namespace app\web\controller;
  2. use Timo\Captcha;
  3. use Timo\Core\Controller;
  4. class VerifyCode extends Controller
  5. {
  6. public function getCaptcha()
  7. {
  8. $Captcha = new Captcha();
  9. Session::set('captcha', $Captcha->getCode());
  10. $Captcha->getImage();
  11. }
  12. }

显示验证码

模版页面,比如登录页面

  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>登录</title>
  5. </head>
  6. <body>
  7. <img src="<?= $this->link('verifyCode/getCaptcha'); ?>" />
  8. </body>
  9. </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();
    }
}