PHP-简单验证码类

以下是做php表单验证过程中,对简单验证码的类的封装使用

  1. 创建一个画布,规定尺寸
  2. 为画布上色
  3. 增加像素点,直线,曲线来增加识别难度
  4. 为验证码truetype的字体设置随机数,自己规定
  5. 最后以想要的图片格式打印出来,用于登录表单

此类,可直接使用,简单易懂,仅供参考学习->

<?php

/**
 * 封装一个输出随机验证码的类
 */
class Verify {
    public $config = array(
        'width' => 70,
        'height' => 45,
        'size' => 20,
        'startx' => 10,
        'starty' => 35,
        'font' => '..//public/font/verdana.ttf'
    );

    /**
     * 初始化,构造函数的传入数组值,可以改变我们的config内容
     * @param $arr
     */
    public function __construct($arr = null)
    {
        if (is_array($arr)) {
            foreach ($arr as $key => $value) {
                if (array_key_exists($key, $this->config)) {
                    $this->config[$key] = $value;
                }
            }
        }
    }


    public function showVc() {
        header('content-type:image/png'); //画布正确显示的header头
        //首先创建一个画布,所有的图形操作都是在画布的基础上展示的,定义宽高
        $draw = imagecreate($this->config['width'], $this->config['height']);
        //给画布上色
        imagecolorallocate($draw, mt_rand(50, 180), mt_rand(20, 180), mt_rand(50, 180));
        //增加一些像素点pixel,干扰识别
        //为随机字体和干扰的点,线进行颜色的设置
        $pixelcolor = imagecolorallocate($draw, mt_rand(0, 80), mt_rand(0, 80), mt_rand(0, 80));
        $linecolor = imagecolorallocate($draw, mt_rand(100, 230), mt_rand(100, 200), mt_rand(100, 200));
        $fontcolor = imagecolorallocate($draw, mt_rand(100, 160), mt_rand(100, 200), mt_rand(100, 170));

        //然后把这些干扰项目画在画布上
        for ($j = 0; $j < 100; $j++) {
            imagesetpixel($draw, mt_rand(0, $this->config['width']), mt_rand(0, $this->config['height']), $pixelcolor);
            if ($j < 4) {
                //画线
                imageline($draw, mt_rand(0, $this->config['width'] / 5), mt_rand(0, $this->config['height']), mt_rand($this->config['width'] / 2, $this->config['width']), mt_rand(0, $this->config['height']), $linecolor);
            }
        }
        imagettftext($draw, $this->config['size'],10, $this->config['startx'], $this->config['starty'],$fontcolor, $this->config['font'], $this->getRandData());
        //输出画布
        imagepng($draw);
}

    /**
     * 返回随机字符
     * @return string
     */
    public function getRandData(){
        $arr1 = range('A','Z');
        $arr2 = range(1,9);
        $arr3 = range('a','z');
        $arr4 = array_merge($arr1,$arr2,$arr3);
        $strData ="";
        for($i=0;$i<4;$i++){
            $index = array_rand($arr4);
            $strData.=$arr4[$index];
        }
        $_SESSION['vc'] = $strData;
        return $strData;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值