php 简单的验证码

注意事项:

验证的隐藏域的位置一定要在调用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;
}

function check()
{
    var chk2 = document.getElementById('chk');
    var chk1 = document.getElementById('check1');
    if(chk2.value == chk1.value)
    {
        return true;
    }
    return false;
}
</script>
</head>
<body>

<form name="login" id="login" method="post" action="res.php" onSubmit="return check();">
<input type="text" name="yzm" value="" id="check1" />
<input type="hidden" name="check2" value="" id="chk" />
<input type="submit" name="submit" value="submit" />
<script>
yzm(login);
</script>
<a href="javascript:void(0)" onclick="coding(login)">change</a>
</form>
</body>
</html>

验证输出图像:yzm.php

<?php

//如果浏览器显示“图像XXX因其本身有错无法显示”,可尽量去掉文中空格
//先成生背景,再把生成的验证码放上去
$img_height=70;//先定义图片的长、宽
$img_width=25;
$authnum='';
//生产验证码字符

$authnum = $_GET['num'];
//把验证码字符保存到session

$aimg = imagecreate($img_height,$img_width);    //生成图片
imagecolorallocate($aimg, 255,255,255);            //图片底色,ImageColorAllocate第1次定义颜色PHP就认为是底色了
$black = imagecolorallocate($aimg, 0,0,0);        //定义需要的黑色


for ($i=1; $i<=100; $i++) {
    imagestring($aimg,1,mt_rand(1,$img_height),mt_rand(1,$img_width),"@",imagecolorallocate($aimg,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)));
}

//为了区别于背景,这里的颜色不超过200,上面的不小于200
for ($i=0;$i<strlen($authnum);$i++){
    imagestring($aimg, mt_rand(5,6),$i*$img_height/4+mt_rand(2,3),mt_rand(1,$img_width/2-2), $authnum[$i],imagecolorallocate($aimg,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200)));
}
imagerectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//画一个矩形
Header("Content-type: image/PNG");
ImagePNG($aimg);                    //生成png格式
ImageDestroy($aimg);
?>

posted @ 2014-02-10 21:04  好记性还真不如烂笔头  阅读(310)  评论(0编辑  收藏  举报