注意事项:
验证的隐藏域的位置一定要在调用JS前。。
如:
<input type="text" name="yzm"
value="" />
<input type="hidden" name="check2" value=""
/>
<script>
yzm(login);
</script>
表单文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta
http-equiv="Content-Type" content="text/html; charset=gb2312"
/>
<title>xxx</title>
<script>
function
yzm(form){
var num1 =
Math.round(Math.random()*10000000);
var num =
num1.toString().substr(0, 4);
document.write("<img
name=code width=‘50‘ height=‘30‘ src=‘yzm.php?num="+num+"‘
/>");
form.check2.value = num;
}
function
coding(form){
var num1 =
Math.round(Math.random()*10000000);
var num =
num1.toString().substr(0, 4);
document.code.src=‘yzm.php?num=‘+num;
form.check2.value =
num;
}
</script>
</head>
<body>
<form
name="login" id="login">
<input type="text" name="yzm" value=""
/>
<input type="hidden" name="check2" value=""
/>
<script>
yzm(login);
</script>
<a href="#"
onclick="coding(login)">change</a>
</form>
</body>
</html>
验证输出图像:yzm.php
<?php
srand((double)microtime()*1000000);
$im=imagecreate(42,16);
$black=imagecolorallocate($im,0,0,0);
$white=imagecolorallocate($im,255,255,255);
$gray=imagecolorallocate($im,200,200,200);
imagefill($im,0,0,$gray);
for($i=0;$i<4;$i++){
$str=mt_rand(1,3);
$size=mt_rand(3,6);
$authnum=substr($_GET[num],$i,1);
imagestring($im,$size,(2+$i*10),$str,$authnum,imagecolorallocate($im,rand(0,130),rand(0,130),rand(0,130)));
}
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);
}
imagepng($im);
imagedestroy($im);
?>