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

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文件,用来显示验证码


<?php
if(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)" οnclick="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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值