php验证码
index.php文件:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" /> <title>用户注册</title> <style> img{ cursor: pointer; } img:hover{ box-shadow:0 0 3px 3px #888; } </style> </head> <body> <h2>用户注册:</h2> <hr> <form action="reg.php" method='post'> <p>用户名:</p> <p> <input type="text" value='user1' name='username'> </p> <p>密码:</p> <p> <input type="password" value='123' name='password'> </p> <p>验证码:</p> <p> <img src="verify.php" onclick="this.src='verify.php?rand='+Math.random()"> </p> <p>输入验证码:</p> <p> <input type="text" name='fcode'> </p> <p> <input type="submit" value="注册"> </p> </form> </body> </html>
reg.php文件:
<?php //开启session才可以取出其他页面放到session数组中的数据 session_start(); //获取表单中人们输入的验证码 $fcode=strtolower($_POST['fcode']); //获取图片中的随机字符串 $vcode=strtolower($_SESSION['vcode']); //把人们输入的验证码和图片中的随机字符串都变成小写,然后进行比对. if($fcode==$vcode){ echo "<h2>{$_POST['username']}注册成功!</h2>"; }else{ echo "<h2>验证码输入有误!</h2>"; } echo "<script>setTimeout(function(){location='index.php'},2000)</script>"; ?>
verify.php文件:
<?php // session是实现多个页面共享数据的 session_start(); // 1.创建画布资源 $img=imagecreatetruecolor(100,30); // 2.准备颜色 $white=imagecolorallocate($img,255,255,255); $blue=imagecolorallocate($img,0,0,255); $gray=imagecolorallocate($img,200,200,200); // 3.在画布上画图像或文字 imagefill($img,0,0,$white); // 随机生成5位字符串 $arr=array_merge(range(0,9),range('a','z'),range('A','Z')); shuffle($arr); $randStr=join('',array_slice($arr,0,5)); //把随机字符串放到session数组中 $_SESSION['vcode']=$randStr; // 4.画点 imagettftext($img,15,0,15,22,$blue,'./msyhbd.ttf',$randStr); // 点干扰素 for($i=0;$i<500;$i++){ imagesetpixel($img,mt_rand(0,100),mt_rand(0,30),$blue); } // 线干扰素 for($j=0;$j<10;$j++){ imageline($img,mt_rand(0,100),mt_rand(0,30),mt_rand(0,100),mt_rand(0,30),$blue); } // 曲线干扰素 for($x=0;$x<10;$x++){ imageellipse($img,mt_rand(0,100),mt_rand(0,30),20,20,$blue); } // 5.输出最终图像或保存最终图像 header('content-type: image/png'); imagepng($img); // 6.释放画布资源 imagedestroy($img); ?>
注意:代码需要一个字体文件,“msyhbd.ttf”是“微软雅黑”字体。字体下载:https://files.cnblogs.com/files/qingsong/msyhbd.ttf.gz

浙公网安备 33010602011771号