<?php
namespace fast; //放到fast目录

use think\Cache;
use think\Response;

//使用
// //获取验证码
// public function logincaptcha()
// {
//     $token = $this->request->get('token'); // 前端生成token,传给后端
//     return \fast\TokenCaptcha::get($token);
// }


// //验证验证码 传入token和验证码
// $token = $this->request->post('token');
// $captcha = $this->request->post('captcha');
// if (!\fast\TokenCaptcha::check($token, $captcha)) {
//     $this->error('验证码有误,请重新输入!');
// }




class TokenCaptcha
{
    const CACHE_PREFIX = 'captcha_token_';
    const EXPIRE = 600;

    /** 生成验证码图片(自己画,字符完全可控) */
    public static function get($token = '')
    {
        $token = $token ?: md5(uniqid(mt_rand(), true));
        $code  = str_pad((string)mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
        Cache::set(self::CACHE_PREFIX . $token, $code, self::EXPIRE);

        $w = 120; $h = 40;
        $im = imagecreatetruecolor($w, $h);
        $bg = imagecolorallocate($im, 255, 255, 255);
        imagefilledrectangle($im, 0, 0, $w, $h, $bg);

        $color = imagecolorallocate($im, 0, 0, 0);
        imagettftext($im, 20, 0, 10, 28, $color, self::font(), $code);

        ob_start();
        imagepng($im);
        $png = ob_get_clean();
        imagedestroy($im);

        return Response::create($png, 'image/png')->header('X-Captcha-Token', $token);
    }

    /** 验证 */
    public static function check($token, $userInput, $delete = true)
    {
        $key  = self::CACHE_PREFIX . $token;
        $real = Cache::get($key);
        if ($real === null) return false;
        $ok = strcasecmp($real, $userInput) === 0;
        if ($ok && $delete) Cache::rm($key);
        return $ok;
    }

    /** 字体路径(系统自带) */
    private static function font()
    {
        return ROOT_PATH  . 'public/assets/fonts/captcha.ttf'; // 或 /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
    }
}

点赞(0)

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部