GD2的实例应用

来源:互联网 发布:羊绒裤 知乎 编辑:程序博客网 时间:2024/05/22 13:10


利用GD2函数创建一个四位的验证码

<?phpsession_start();header("content-type:image/png");$image_width=70;$image_height=18;srand(microtime()*100000); //microtime函数返回当前时间戳,设置随机数的种子for($i=0;$i<4;$i++){$new_number.=dechex(rand(0,15));//循环输出4位随机数}$_SESSION[check_checks]=$new_number;//将获取的随机验证码写入session变量中$num_image=imagecreate($image_width,$image_height);//创建画布imagecolorallocate($num_image,255,255,255);//设置画布颜色for($i=0;$i<strlen($_SESSION[check_checks]);$i++){//循环读取session中的验证码$font=mt_rand(3,5);//设置随机字体$x=mt_rand(1,8)+$image_width*$i/4;//设置随机字符的X坐标$y=mt_rand(1,$image_height/4);//设置随机字符的Y坐标$color=imagecolorallocate($num_image,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));//设置字符颜色imagestring($num_image,$font,$x,$y,$_SESSION[check_checks][$i],$color);//水平输出字符}imagepng($num_image);//生成png格式的图像imagedestroy($num_image);//释放图像资源?>

判断验证码是否正确

<?phpsession_start();if($_POST["submit"]!=""){$checks=$_POST["checks"];if($checks==""){echo "<script><alert("验证码不能为空");window.location.href='index.php';</script>";}if($checks==$_SESSION[check_checks]){echo "<script><alert("用户登录成功");window.location.href='index.php';</script>";}esle{echo "<script><alert("你输入的验证码不正确");window.location.href='index.php';</script>";}}?>








原创粉丝点击