php 验证码步骤和代码

来源:互联网 发布:思科软件下载 编辑:程序博客网 时间:2024/06/01 12:46
<?php    
//本类只提供用php产生验证码的方法,不提供js代码,
//本类开源,是我无聊的时候写的,希望能够帮到你
//1:设置验证码属性
//2: 绘制基本框架
//3:产生随机字符串
//4:添加干扰
//5:绘制完成产生图片
class Verification
{
    //1:设置验证码属性
    private $border = 0;//边框
    private $num = 4;//验证码位数
    private $width = 60 ;//验证码宽度
    private $higth = 20;//图片高度
    private $fontsize = 6;//字体大小
    private $content = "qwertyuiopasdfghjklzxcvbnm123456789";//验证码源
    private $str = "";//当前字符串
    public function __construct()
    {
        srand((double)microtime()*1000000); //初始化随机数种子;
    }

    //2: 绘制基本框架
    //2.1创建图片
    private function create()
    {
        $img = ImageCreate($this ->width,$this -> higth);
        return $img;
    }
    //2.2填充颜色
    private function color()
    {
        $img = $this -> create();
        $bgcolor = ImageColorAllocate($img,255,255,255);//设置背景颜色
        ImageFill($img,0,0,$bgcolor);
        //设置边框颜色
        if($this -> border)
        {
            $bordercolor = ImageColorAllocate($img,0,0,0);
            ImageRectangle($img,0,0,$this -> width -1,$this -> higth -1,$bordercolor);
        }
        return $img;
    }






    //3:产生随机字符串
    private function randstr()
    {    $str = "";
        $img = $this -> color();
        
        for($i =0;$i<$this -> num;$i++)
        {
            $which = mt_rand(0,strlen($this -> content)-1 );
            $code = substr($this -> content,$which,1);
            $j = $i*15+2; //绘字符位置
            $color  = ImageColorAllocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
            ImageChar($img,$this -> fontsize,$j,3,$code,$color);
            $str .= $code;
        }
        $array = array();
        $array["img"] = $img;
        $array["str"] = $str;
        return $array;
    }
    //4:添加干扰
    public function disturbance()
    {
        $array = $this -> randstr();
        //添加干扰线
        for($i = 0;$i < $this -> num;$i++)
        {
            $color1 = ImageColorAllocate($array["img"],mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            ImageArc($array["img"], mt_rand(-5,$this -> width), mt_rand(-5,$this -> higth), mt_rand(20,300), mt_rand(20,200), 55, 44, $color1); //干扰线
        }
        for($i = 0;$i < $this -> num * 40;$i++)
        {
            $color2 = ImageColorAllocate($array["img"],mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            ImageSetPixel($array["img"] ,mt_rand(-5,$this -> width), mt_rand(-5,$this -> higth), $color2); //干扰点
        }
//        return $this -> num;
        return $array;

    }

    
    
}
//Header("Content-type: image/gif");
//$obj = new Verification();
//$array = $obj -> disturbance();

//Imagegif($array["img"]);
//ImageDestroy($array["img"]);
//echo $array["str"];



?>

原创粉丝点击