PHPmvc封装英文验证码生成

释放双眼,带上耳机,听听看~!

最近在学习深入学习手撸PHPmvc框架,目前进度到了英文验证码这一块了,怕以后可能会用到所以mark下来。

<?php
/**
 * Created by PhpStorm.
 * User: nobita
 * Date: 8/18
 * Time: 17:52
 */

class CaptchaLib
{
    private $length;
    private $font=5;
    public function __construct($length=4,$font=5)
    {
        $this->length = $length;
        $this->font = $font;
    }

    private function generalCode(){
        $charArray = array_merge(range('A','Z'),range('a','z'),range(0,9));
        $index = array_rand($charArray,4);
        shuffle($index);
        $str='';
        foreach ($index as $i){
            $str .= $charArray[$i];
        }
        return $str;
    }

    public function generalCaptcha(){
        $code = $this->generalCode();
        $_SESSION['code'] = $code;
        $bgPath = LIB_PATH.'captcha/captcha.jpg';
        $img = imagecreatefromjpeg($bgPath);
        $color = imagecolorallocate($img,0,0,0);
        if (rand(1,2) == 2)
            $color = imagecolorallocate($img,255,255,255);
        $x = (imagesx($img)-imagefontwidth($this->font)*strlen($code))/2;
        $y = (imagesy($img)-imagefontheight($this->font))/2;
        imagestring($img,$this->font,$x,$y,$code,$color);
        header('content-type:image/png');
        imagepng($img);
        imagedestroy($img);
    }

    public function checkCaptcha($code){
        return strtolower($code) == strtolower($_SESSION['code']);
    }
}

控制器中校验验证码

$captcha = new CaptchaLib();
            $code = $_POST['captcha'];
            if (!$captcha->checkCaptcha($code)){
                return $this->error('/index.php?p=admin&c=login&a=index','验证码错误!');
            }

人已赞赏
知识分享

form的onsubmit事件

2020-7-4 13:34:00

知识分享

使用递归获取无限级树分类

2020-7-6 13:36:00

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索