一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

PHP图形验证码生成代码与包括Ajax验证实例应用

时间:2010-07-26 编辑:简简单单 来源:一聚教程网

有3个文件:
authcode.php-----验证码的生成php文件
authcode.html-----前台显示页面
dealauthcode.php-----ajax提交到的后台处理判断验证码是否正确的处理页面
*/
?>

前台调用验证码代码

 代码如下 复制代码





验证码ajax验证






       
       
验证码:



dealauthcode.php-----ajax提交到的后台处理判断验证码是否正确的处理页面

 代码如下 复制代码
        session_start();
       $authcode = $_get['authcode'];
//这里的$_session['authcode']是在验证码authcode页面产生的
if(strtoupper($authcode)!= $_session['authcode']){   
echo 'mis_match';       
        }
?>
 


生成验证码程序 authcode.php文件

 代码如下 复制代码

        session_start ();
        header ( 'content-type: image/png' );
        //创建图片
        $im = imagecreate($x=130,$y=45 );
        $bg = imagecolorallocate($im,rand(50,200),rand(0,155),rand(0,155));

//第一次对 imagecolorallocate() 的调用会给基于调色板的图像填充背景色
        $fontcolor = imagecolorallocate ( $im, 255, 255, 255 );            

            //字体颜色
        $fontstyle = 'rock.ttf';                                           

                             //字体样式文件,这个文件是从我们

c:windows onts下的字体中随便选一个出来的,你们也可以替换其他的!
        //产生随机字符
        for($i = 0; $i < 4; $i ++) {
                $randasciinumarray         = array (rand(48,57),rand

(65,90));
                $randasciinum                 = $randasciinumarray [rand (

0, 1 )];
                $randstr                         = chr ( $randasciinum );
                imagettftext($im,30,rand(0,20)-rand(0,25),5+$i*30,rand

(30,35),$fontcolor,$fontstyle,$randstr);
                $authcode                        .= $randstr;
        }
        $_session['authcode']        = $authcode;
        //干扰线
        for ($i=0;$i<8;$i++){
                $linecolor        = imagecolorallocate($im,rand

(0,255),rand(0,255),rand(0,255));
                imageline ($im,rand(0,$x),0,rand(0,$x),$y,$linecolor);
        }
        //干扰点
        for ($i=0;$i<250;$i++){
                imagesetpixel($im,rand(0,$x),rand(0,$y),$fontcolor);
        }
        imagepng($im);
        imagedestroy($im); 
  


  /*
  注册的时候常常会用到注册码来防止机器恶意注册,这里我发表一个产生png图片验证码的基本图像,很简陋但思想很清晰:
1、产生一张png的图片
2、为图片设置背景色
3、设置字体颜色和样式
4、产生4位数的随机的验证码
5、把产生的每个字符调整旋转角度和位置画到png图片上
6、加入噪点和干扰线防止注册机器分析原图片来恶意注册
7、输出图片
8、释放图片所占内存

热门栏目