PHP验证码之字符验证

来源:互联网 发布:ios编程语言 编辑:程序博客网 时间:2024/06/06 17:31

本篇主要介绍一下关于php在提交表单的时候为了防止机器操作或者是恶意的攻击,在填写表单的时候一般都用验证码来过滤掉一些非法提交数据,首先先来介绍一下关于简单的字母加数字组成的验证码,这类验证码实现相对简单。来看下面的例子:

首先创建一个名为captcha.php的文件用来生成验证码:

<?php//因为要把产生的验证码保存到session中,此处为session开始session_start();//创建一张宽100高30的图像$image = imagecreatetruecolor(100, 30);//为$image设置背景颜色为白色$bgcolor = imagecolorallocate($image, 255, 255, 255);//填充背景颜色imagefill($image, 0, 0, $bgcolor);//生成4个随机数/*for($i=0; $i<4; $i++){//设置字体为6$fontsize=6;//设置背景颜色为随机颜色 三个rand()函数分别对应颜色的rgb让他们产生在0~120这个范围的数值$fontcolor=imagecolorallocate($image, rand(0,120), rand(0, 120), rand(0,120));//生成随机数字$fontcontent=rand(0, 9);//控制数字出现的位置x->left y->top$x=($i*100/4)+rand(5, 10);$y=rand(5, 10);imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);}*/$captch_code="";for($i=0; $i<4; $i++){$fontsize=6;$fontcolor=imagecolorallocate($image, rand(0,120), rand(0,120), rand(0, 120));$data="1234567890abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";//设置每次产生的字符从$data中每次截取一个字符$fontcontent=substr($data, rand(0,strlen($data)), 1);//让产生的四个字符拼接起来$captch_code.=$fontcontent;//控制每次出现的字符的坐标防止相互覆盖即x->left y->top$x=($i*100/4)+rand(5, 10);$y=rand(5, 10);//此函数用来将产生的字符在背景图上画出来imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);}$_SESSION['authcode']=$captch_code;//把产生的验证码存入session中//用来在背景图片上产生200个干扰点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++) { # code...//干扰线的颜色$linecolor=imagecolorallocate($image, rand(80, 220), rand(80, 220), rand(80, 220));//画出每条干扰线imageline($image, rand(1, 99), rand(1, 29), rand(1, 99), rand(1,29), $linecolor);}//设置header图片格式为pngheader('content-type:image/png');//显示图片imagepng($image);//destoryimagedestroy($image);?>
此时该文件已经能够产生相应的验证码,然后把它加到相应的表单文件中,本例中用form.php用来存放表单代码:

<?php//设置头header('content-type:text/html;charset=utf-8');if(isset($_REQUEST['authcode'])){session_start();//将表单中填写得验证码全部转化为小写与存在session中的比较是否相等if(strtolower(trim($_REQUEST['authcode'])) == $_SESSION['authcode']){echo '<font color="#0000CC">输入正确</font>';}else{echo '<font color="#CC0000"> <b>输入错误</b> </font>';}exit();}?><!DOCTYPE html><html><head><meta charset="utf-8" /><title>确认验证码</title></head><body><form method="post" action="./form.php"><p>验证码图片:<img  id="captcha_img" border="1" src="./captcha.php?r=<?php echo rand();?>" width:100px; height:30px" /><!--用javascript添加一个动态刷新链接只改变传递的自定义参数--><a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='./captcha.php?r=Math.random()'">换一个?</a></p><p>请输入图片中的内容:<input type="text" name="authcode" value"" /></p><p><input type="submit" value="提交" style="padding:6px 20px;"></p></form></body></html>

效果图如下:



0 0
原创粉丝点击