使用PHP制作一个验证码

来源:互联网 发布:miui msa是什么软件 编辑:程序博客网 时间:2024/06/06 12:51
 * 验证码
 * @param   int $type  验证码类型  1纯数字  2小写字母  3大写字母  4 大小写字母混合  5 数字和字母混合
 * @param   int $length 验证码长度
 * @param   int $width   验证码图像宽度
 * @param   int $height  验证码图像高度
 */


function verifyCode($type=1,$length=4,$width=100,$height=40){
//第一步:创建画布,获取图像资源
    $img=imagecreatetruecolor($width,$height);
//第二步:操作图像资源
//分配背景色
    $backColor=imagecolorallocate($img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
//填充背景颜色
    imagefill($img,0,0,$backColor);
//随机生成字符串
    $str=getRandStr($type,$length);
    //将产生的随机字符串存入session
    $_SESSION['yh_verify']=$str;


//分配文字颜色
    $fontColor=imagecolorallocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
//准备字体
    $fonts=array('msyh.ttf','msyhbd.ttf','simhei.ttf');
    $font='fonts/'.$fonts[array_rand($fonts)];
//写入字符串
    imagettftext($img,mt_rand(20,25),mt_rand(-10,10),mt_rand(5,10),mt_rand(25,30),$fontColor,$font,$str);
//写点干扰项
    for($i=1;$i<=500;$i++){
        imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($img,mt_rand(50,150),mt_rand(50,150),mt_rand(50,150)));
    }
//写线干扰项
    for($n=1;$n<=20;$n++){
        $x=mt_rand(0,$width);
        $y=mt_rand(0,$height);
        imageline($img,$x,$y,$x+rand(-50,50),$y+rand(-50,50),imagecolorallocate($img,mt_rand(50,150),mt_rand(50,150),mt_rand(50,150)));
    }
//第三步:输出图像
    header('Content-type:image/png');
    imagepng($img);
//第四步:销毁图像资源,释放内存
    imagedestroy($img);
}
原创粉丝点击