生成验证码,并对验证码进行验证
两个文件,test.php与gd.php
gd.php为生成验证码,是否做干扰线条等,可按注释修改。
test.php对验证码进行验证,原理是通过session比较,如果要忽略大小写,可通过strtolower判断,只要数字验证,可修改红色字体
test.php代码如下:
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
<?php
session_start();
if(isset($_SESSION['authnum'])&&isset($_POST['authcode']))
{
if($_SESSION['authnum']==$_POST['authcode'])
{
echo “<script>alert(‘验证码输入正确!’);</script>”;
}
else
{
echo “<script>alert(‘验证码输入错误!’);</script>”;
}
}
?>
<SCRIPT LANGUAGE=”JavaScript”>
function chang_img()
{
document.getElementById(‘img’).src=”gd.php”;
}
</SCRIPT>
<FORM METHOD=’POST’ ACTION=”test.php”>
<input type=”text” name=”authcode” id=”textfield”/>
<img id=”img” src = “gd.php” onclick=”chang_img()”/><br />看不清单击验证码
<INPUT TYPE=”submit” value=”提交” />
</FORM>
gd.php代码如下:
<?php
session_start();
//生成验证码图片
Header(“Content-type: image/PNG”);
srand((double)microtime()*1000000);//播下一个生成随机数字的种子
$_SESSION['authnum']=”";
$im = imagecreate(70,21) or die(“Cant’s initialize new GD image stream!”); //制定图片背景大小
$black = ImageColorAllocate($im, 0,0,0); //设定三种颜色
$white = ImageColorAllocate($im, 255,255,255);
$gray = ImageColorAllocate($im, 200,200,200);
imagefill($im,0,0,$gray); //采用区域填充法,设定(0,0)
//生成数字和字母混合的验证码方法
$ychar=”0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z”;
$list=explode(“,”,$ychar);
for($i=0;$i<4;$i++){
$randnum=rand(0,35);
$authnum.=$list[$randnum];
}
$_SESSION['authnum']=$authnum;
imagestring($im, 5, 10, 3, $authnum, $black);
//加入干扰象素
for($i=0;$i<200;$i++)
{
$randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
}
//加入3条干扰线;也可以不要;视情况而定,因为可能影响用户输入;
$li = ImageColorAllocate($im, 0,0,0);
for($i=0;$i<3;$i++)
{
//imageline($im,rand()%70,rand()%30,rand()%70,rand()%30,$li);
}
ImagePNG($im);
ImageDestroy($im);
?>
