PHP验证码开发

简介:自己封装的验证码类,简单的介绍一下验证码的工作原理

验证码开发,啥也不说了直接上代码吧

class Validatecode
{
    //画布对象
    private $img;
    //设置字体大小(大于5时使用自定义字体)
    public $fontsize = 5;
    /* *
     *  构造函数
     *  创建画布并分配底色
     *  参数为画布底色的rgb值
     * */
    public function __construct($weight=100,$height=30,$r=255,$g=255,$b=255)
    {
        //申明返回图片
        header("content-type:image/png");
        //创建画布
        $this->img = imagecreatetruecolor($weight, $height);
        //为画布分配颜色
        $bgcolor = imagecolorallocate($this->img, $r, $g, $b);
        //填充颜色
        imagefill($this->img, 0, 0, $bgcolor);
    }
    /* *
     *  添加字体
     * */
    public function addText($fontnum=5)
    {
        $font = null;
        for ($i=0;$i<$fontnum;$i++)
        {
            //为字体分配颜色
            $fontcolor = imagecolorallocate($this->img,rand(0,125),rand(0,125),rand(0,125));
            //设置字体内容
            $str = "qwertyuipasdfghjkxcvbnm3456789";
            $fontcontent = substr($str,rand(0,30),1);
            $font .= $fontcontent;
            //设置字体的x轴位置
            $x = ($i*100/$fontnum)+$fontcontent;
            //设置字体的y轴位置
            $y = rand(5,10);
            //填充字体
            //一下两种方式任选一种
            imagechar($this->img, $this->fontsize, $x, $y, $fontcontent, $fontcolor);
            //imagestring($this->img, $this->fontsize, $x, $y, $fontcontent, $fontcolor);
        }
        return $font;
    }
    /* *
     *  添加点干扰元素
     * */
    public function addPoint($pointnum=200)
    {
        for ($i=0;$i<$pointnum;$i++)
        {
            //为点分配颜色
            $pointcolor = imagecolorallocate($this->img,rand(0,125),rand(0,125),rand(0,125));
            //填充点
            imagesetpixel($this->img, rand(1,99), rand(1,29), $pointcolor);
        }
    }
    /* *
     *  添加线干扰元素
     * */
    public function addLine($linenum=4)
    {
        for ($i=0;$i<$linenum;$i++)
        {
            //为点分配颜色
            $pointcolor = imagecolorallocate($this->img,rand(0,125),rand(0,125),rand(0,125));
            //填充线
            imageline($this->img, rand(1,99), rand(1,29), rand(1,99), rand(1,29), $pointcolor);
        }
    }
    /* *
     *  输出图片并释放资源
     * */
    public function showValidate()
    {
        imagepng($this->img);
        imagedestroy($this->img);
    }
    /* *
     *  析构函数,防止调用者未输出图片和释放资源
     *  输出图片并释放资源
     * */
    public function __destruct()
    {
        if($this->img){
            imagepng($this->img);
            imagedestroy($this->img);
        }
    }
}
编程经验共享公众号二维码
更多内容关注公众号
Copyright © 2021 编程经验共享 赣ICP备2021010401号-1