index.html
<td><input type="text" autocomplete="off" class="myinput" id="code" name="code" style="width:100px;float:left;" />
<div class="code-img"><img src="yanzhengma.php" alt="看不清换一张" onclick="javascript:this.src='yanzhengma.php?tm='+Math.random()" /></div></td>
yanzhengma.php
<?php
session_start();IamgeCode(4,100,30);
function IamgeCode($num,$x,$y){
//生成验证码图片
Header("Content-type: image/PNG");
$codenum = ($num=='')? 4 : $num;
$x_w = ($x=='')? 70 : $x;
$y_h = ($y=='')? 20 : $y;
srand((double)microtime()*1000000);//播下一个生成随机数字的种子,以方便下面随机数生成的使用
//将随机数存入session中
$_SESSION['authnum']="";
$im = imagecreate($x_w,$y_h) 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,10,10,$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";
$ychar = "0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9";
$list = explode(",",$ychar);
for($i=0;$i<$codenum;$i++){
$randnum=rand(0,39);
$authnum.=$list[$randnum];
}
$_SESSION['authnum']=$authnum;
//imagestring($im,5, 14, 4, $authnum, $black);
for($k=0;$k<60;$k++) //加入干扰象素
{
$randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
}
for ($i=0;$i<$codenum;$i++)
{
$bg_color = imagecolorallocate ($im, rand(0,255), rand(0,128), rand(0,255));
$x = floor($x_w/$codenum)*$i;
$y = rand(0,$y_h-15);
imagechar ($im, 5, $x, $y, $authnum[$i], $bg_color);
}
ImagePNG($im);
ImageDestroy($im);
}
?>