php实现简单验证码并且验证

来源:互联网 发布:如何找回淘宝聊天记录 编辑:程序博客网 时间:2024/05/17 08:01
1、新建一个validatecode.hphp
<?php/** * Created by PhpStorm. * User: Administrator * Date: 2016/4/26 * Time: 11:39 */session_start();//必须放在脚本的最顶端$image = imagecreate(100, 30);//绘制一张100*30的图像$bgcolor=imagecolorallocate($image,255,255,255);//设置图片背景颜色imagefill($image,0,0,$bgcolor);//将背景颜色添加至图像中$capth_code='';/** * 生成一个随机数字*///for($i=0;$i<4;$i++){//    $fontSize=6;//    $fontColor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));//    $fontContent=rand(0,9);//    $x=($i*100/4)+rand(5,10);//    $y=rand(5,10);//    //按照一定比例排列到图片上//    imagestring($image,$fontSize,$x,$y,$fontContent,$fontColor);//}/** * 生成数字和字母混合的验证码 */for($i=0;$i<4;$i++){    $fontsize=8;    $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));    $data='qwertyuipasdfghjkzxcvbnm23456789';    $fontcontent=substr($data,rand(0,strlen($data)),1);    $capth_code=$fontcontent;        $x=($i*100/4)+rand(5,10);    $y=rand(5,10);    //按照一定比例排列到图片上    imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);}$_SESSION['autocode']=$capth_code;/** * 绘制干扰元素 */for($i=0;$i<200;$i++){    $pointColor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));    imagesetpixel($image,rand(1,99),rand(1,29),$pointColor);}/** * 为验证码添加干扰线 */for($i=0;$i<3;$i++){    $lineColor=imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,200));    imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$lineColor);}header('content-type:image/png');//使用header发送图像imagepng($image);//显示图像imagedestroy($image);//销毁图像


2.新建一个form.php文件,用来显示验证码


<?phpif(isset($_REQUEST['autocode'])){    session_start();    if(strtolower($_REQUEST['autocode'])==$_SESSION['autocode']){        echo '输入正确';    }    else{        echo '输入错误';    }}?><html><meta charset="utf-8"><title>验证码验证</title><link rel="stylesheet" type="text/css" href="bootstrap.min.css"><script>    function test(){        document.getElementById('captcha_img').src='./validatecode.php?r='+Math.random();    }</script><body><form method="post" action="./form.php">    <p>验证码    <img  id="captcha_img" src="./validatecode.php?r=<?php echo rand();?>" border="1" width="100px"><a href="javascript:void(0)" onclick="test();">换一个?</a>    </p><p>请输入图中的验证码:<input type="text" name="autocode" value=""></p>    <p><input type="submit" value="提交" style="padding: 6px 20px" class="btn bg-danger"></p></form></body></html>


0 0