php实现动态随机验证码机制(CAPTCHA)

WBOY
发布: 2016-08-08 09:30:01
原创
1040 人浏览过

php实现动态随机验证码机制

      验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。

      这个问题可以由计算机生成并评判,但是必须只有人类才能解答。由于计算机无法解答CAPTCHA的问题,所以回答出问题的用户就可以被认为是人类。

      Php制作动态验证码是基于php的图像处理,下面首先介绍一下php的图像处理。

一.php图像处理简介

      在PHP5中,动态图象的处理要比以前容易得多。PHP5在php.ini文件中包含了GD扩展包,只需去掉GD扩展包的相应注释就可以正常使用了。PHP5包含的GD库正是升级的GD2库,其中包含支持真彩图像处理的一些有用的JPG功能。

      一般生成的图形,通过PHP的文档格式存放,但可以通过HTML的图片插入方式SRC来直接获取动态图形。比如,验证码、水印、微缩图等。

      创建图像的一般流程:

1).设定标头,告诉浏览器你要生成的MIME类型。

2).创建一个图像区域,以后的操作都将基于此图像区域。

3).在空白图像区域绘制填充背景。

4).在背景上绘制图形轮廓输入文本。

5).输出最终图形。

6).清除所有资源。

7).其他页面调用图像。

第一步,设置文件MIME类型,输出类型 将输出类型改成图像流

header('Content-Type: image/png;');

一般生成的图像可以是png,jpeg,gif,wbmp

第二步,创建一个图形区域,图像背景

imagecreatetruecolor() 返回一个图像标识符,代表了一幅大小为 x_sizey_size 的黑色图像。语法:resource imagecreatetruecolor ( int $width , int $height )

$im = imagecreatetruecolor(200,200);

第三步,在空白图像区域绘制填充背景

要有颜色填充器;imagecolorallocate -- 为一幅图像分配颜色;语法:int imagecolorallocate ( resource $image , int $red , int $green , int $blue )

$blue = imagecolorallocate($im,0,102,255);

将这个blue颜色填充到背景上去;imagefill -- 区域填充;语法:bool imagefill ( resource $image , int $x , int $y , int $color )

imagefill($im,0,0,$blue);

第四步,在蓝色的背景上输入一些线条,文字等

颜色填充器

$white = imagecolorallocate($im,255,255,255);

画两条线段:imageline

imageline() 用 color 颜色在图像 image 中从坐标 x1y1x2y2(图像左上角为 0, 0)画一条线段。语法:bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

imageline($im,0,0,200,200,$white);

imageline($im,200,0,0,200,$white);

水平地画一行字符串:imagestring

imagestring() 用 col 颜色将字符串 s 画到 image 所代表的图像的 xy 坐标处(这是字符串左上角坐标,整幅图像的左上角为 0,0)。如果font 是 1,2,3,4 或 5,则使用内置字体。语法:bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col )

imagestring($im,5,66,20,'jingwhale',$white);

第五步,输出最终图形

imagepng() 将 GD 图像流(image)以 PNG 格式输出到标准输出(通常为浏览器),或者如果用 filename 给出了文件名则将其输出到该文件。语法:bool imagepng ( resource $image [, string $filename ] )

imagepng($im);

第六步,我要将所有的资源全部清空

imagedestroy() 释放与 image 关联的内存。语法:bool imagedestroy ( resource $image )

imagedestroy($im);

其他页面(html)调用创建的图形

示例代码如下:

<span>php
    </span><span>//</span><span>第一步,设置文件MIME类型</span>
    <span>header</span>('Content-Type: image/png;'<span>);
    
    </span><span>//</span><span>第二步,创建一个图形区域,图像背景</span>
    <span>$im</span> = imagecreatetruecolor(200,200<span>);
    
    </span><span>//</span><span>第三步,在空白图像区域绘制填充背景</span>
    <span>$blue</span> = imagecolorallocate(<span>$im</span>,0,102,255<span>);    
    imagefill(</span><span>$im</span>,0,0,<span>$blue</span><span>);
    
    </span><span>//</span><span>第四步,在蓝色的背景上输入一些线条,文字等</span>
    <span>$white</span> = imagecolorallocate(<span>$im</span>,255,255,255<span>);
    imageline(</span><span>$im</span>,0,0,200,200,<span>$white</span><span>);
    imageline(</span><span>$im</span>,200,0,0,200,<span>$white</span><span>);
    imagestring(</span><span>$im</span>,5,66,20,'Jing.Whale',<span>$white</span><span>);
    
    </span><span>//</span><span>第五步,输出最终图形</span>
    imagepng(<span>$im</span><span>);
    
    </span><span>//</span><span>第六步,我要将所有的资源全部清空</span>
    imagedestroy(<span>$im</span><span>);    
</span>?>
登录后复制

显示效果:

二.创建动态验证码

附:代码源地址https://github.com/cnblogs-/php-captcha

1. 创建带验证码的图片,并模糊背景

随机码采用16进制;模糊背景即在图片背景加上线条、雪花等。

1)创建随机码
  

<span>for</span> (<span>$i</span>=0;<span>$i</span>$_rnd_code;<span>$i</span>++<span>) {
        </span><span>$_nmsg</span> .= <span>dechex</span>(<span>mt_rand</span>(0,15<span>));
    }</span>
登录后复制

string dechex ( int $number ),返回一字符串,包含有给定 number 参数的十六进制表示。

2)保存在session
 

<span>$_SESSION</span>['code'] = <span>$_nms</span>
登录后复制

3)创建图片

<span>//</span><span>创建一张图像</span>
<span>$_img</span> = imagecreatetruecolor(<span>$_width</span>,<span>$_height</span><span>);

</span><span>//</span><span>白色</span>
<span>$_white</span> = imagecolorallocate(<span>$_img</span>,255,255,255<span>);

</span><span>//</span><span>填充</span>
imagefill(<span>$_img</span>,0,0,<span>$_white</span><span>);

</span><span>if</span> (<span>$_flag</span><span>) {
</span><span>//</span><span>黑色,边框</span>
    <span>$_black</span> = imagecolorallocate(<span>$_img</span>,0,0,0<span>);
    imagerectangle(</span><span>$_img</span>,0,0,<span>$_width</span>-1,<span>$_height</span>-1,<span>$_black</span><span>);
}</span>
登录后复制

4)模糊背景

<span>//</span><span>随即画出6个线条</span>
<span>for</span> (<span>$i</span>=0;<span>$i</span>$i++<span>) {
</span><span>   $_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(0,255),<span>mt_rand</span>(0,255),<span>mt_rand</span>(0,255<span>));
   imageline(</span><span>$_img</span>,<span>mt_rand</span>(0,<span>$_width</span>),<span>mt_rand</span>(0,<span>$_height</span>),<span>mt_rand</span>(0,<span>$_width</span>),<span>mt_rand</span>(0,<span>$_height</span>),<span>$_rnd_color</span><span>);
   }

</span><span>//随机</span><span>雪花</span>
<span>for</span> (<span>$i</span>=0;<span>$i</span>$i++<span>) {
   </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(200,255),<span>mt_rand</span>(200,255),<span>mt_rand</span>(200,255<span>));
   imagestring(</span><span>$_img</span>,1,<span>mt_rand</span>(1,<span>$_width</span>),<span>mt_rand</span>(1,<span>$_height</span>),'*',<span>$_rnd_color</span><span>);
   }</span>
登录后复制

5)输出及销毁

<span>//</span><span>输出验证码</span>
<span>for</span> (<span>$i</span>=0;<span>$i</span>strlen(<span>$_SESSION</span>['code']);<span>$i</span>++<span>) {
        </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(0,100),<span>mt_rand</span>(0,150),<span>mt_rand</span>(0,200<span>));
        imagestring(</span><span>$_img</span>,5,<span>$i</span>*<span>$_width</span>/<span>$_rnd_code</span>+<span>mt_rand</span>(1,10),<span>mt_rand</span>(1,<span>$_height</span>/2),<span>$_SESSION</span>['code'][<span>$i</span>],<span>$_rnd_color</span><span>);
    }

</span><span>//</span><span>输出图像</span>
<span>header</span>('Content-Type: image/png'<span>);
imagepng(</span><span>$_img</span><span>);

</span><span>//</span><span>销毁</span>
imagedestroy(<span>$_img</span>);
登录后复制

将其封装在global.func.php全局函数库中,函数名为_code(),以便调用。我们将设置$_width ,$_height ,$_rnd_code,$_flag 四个参数,以增强函数的灵活性。

* @param int $_width 验证码的长度:如果要6位长度推荐75+50;如果要8位,推荐75+50+50,依次类推
* @param int $_height 验证码的高度
* @param int $_rnd_code 验证码的位数
* @param bool $_flag 验证码是否需要边框:true有边框, false无边框(默认)

封装后的代码如下:

<span>php 
</span><span>/*</span><span>*
 *      [verification-code] (C)2015-2100 jingwhale.
 *      
 *      This is a freeware
 *      $Id: global.func.php 2015-02-05 20:53:56 jingwhale$
 </span><span>*/</span>
登录后复制
<span>/*</span><span>*
 * _code()是验证码函数
 * @access public
 * @param int $_width 验证码的长度:如果要6位长度推荐75+50;如果要8位,推荐75+50+50,依次类推
 * @param int $_height 验证码的高度
 * @param int $_rnd_code 验证码的位数
 * @param bool $_flag 验证码是否需要边框:true有边框, false无边框(默认)
 * @return void 这个函数执行后产生一个验证码
 </span><span>*/</span>
<span>function</span> _code(<span>$_width</span> = 75,<span>$_height</span> = 25,<span>$_rnd_code</span> = 4,<span>$_flag</span> = <span>false</span><span>) {

    </span><span>//</span><span>创建随机码</span>
    <span>for</span> (<span>$i</span>=0;<span>$i</span>$_rnd_code;<span>$i</span>++<span>) {
        </span><span>$_nmsg</span> .= <span>dechex</span>(<span>mt_rand</span>(0,15<span>));
    }

    </span><span>//</span><span>保存在session</span>
    <span>$_SESSION</span>['code'] = <span>$_nmsg</span><span>;

    </span><span>//</span><span>创建一张图像</span>
    <span>$_img</span> = imagecreatetruecolor(<span>$_width</span>,<span>$_height</span><span>);

    </span><span>//</span><span>白色</span>
    <span>$_white</span> = imagecolorallocate(<span>$_img</span>,255,255,255<span>);

    </span><span>//</span><span>填充</span>
    imagefill(<span>$_img</span>,0,0,<span>$_white</span><span>);

    </span><span>if</span> (<span>$_flag</span><span>) {
        </span><span>//</span><span>黑色,边框</span>
        <span>$_black</span> = imagecolorallocate(<span>$_img</span>,0,0,0<span>);
        imagerectangle(</span><span>$_img</span>,0,0,<span>$_width</span>-1,<span>$_height</span>-1,<span>$_black</span><span>);
    }

    </span><span>//</span><span>随即画出6个线条</span>
    <span>for</span> (<span>$i</span>=0;<span>$i</span>$i++<span>) {
        </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(0,255),<span>mt_rand</span>(0,255),<span>mt_rand</span>(0,255<span>));
        imageline(</span><span>$_img</span>,<span>mt_rand</span>(0,<span>$_width</span>),<span>mt_rand</span>(0,<span>$_height</span>),<span>mt_rand</span>(0,<span>$_width</span>),<span>mt_rand</span>(0,<span>$_height</span>),<span>$_rnd_color</span><span>);
    }

    </span><span>//</span><span>随即雪花</span>
    <span>for</span> (<span>$i</span>=0;<span>$i</span>$i++<span>) {
        </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(200,255),<span>mt_rand</span>(200,255),<span>mt_rand</span>(200,255<span>));
        imagestring(</span><span>$_img</span>,1,<span>mt_rand</span>(1,<span>$_width</span>),<span>mt_rand</span>(1,<span>$_height</span>),'*',<span>$_rnd_color</span><span>);
    }

    </span><span>//</span><span>输出验证码</span>
    <span>for</span> (<span>$i</span>=0;<span>$i</span>strlen(<span>$_SESSION</span>['code']);<span>$i</span>++<span>) {
        </span><span>$_rnd_color</span> = imagecolorallocate(<span>$_img</span>,<span>mt_rand</span>(0,100),<span>mt_rand</span>(0,150),<span>mt_rand</span>(0,200<span>));
        imagestring(</span><span>$_img</span>,5,<span>$i</span>*<span>$_width</span>/<span>$_rnd_code</span>+<span>mt_rand</span>(1,10),<span>mt_rand</span>(1,<span>$_height</span>/2),<span>$_SESSION</span>['code'][<span>$i</span>],<span>$_rnd_color</span><span>);
    }

    </span><span>//</span><span>输出图像</span>
    <span>header</span>('Content-Type: image/png'<span>);
    imagepng(</span><span>$_img</span><span>);

    </span><span>//</span><span>销毁</span>
    imagedestroy(<span>$_img</span><span>);
}
</span>?>
登录后复制
2.创建验证机制

创建php验证页面,通过session来检验验证码是否一致。

1)创建verification-code.php验证页面

<span>php 
</span><span>/*</span><span>*
 *      [verification-code] (C)2015-2100 jingwhale.
 *
 *      This is a freeware
 *      $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$
 </span><span>*/</span>

<span>//</span><span>设置字符集编码</span>
<span>header</span>('Content-Type: text/html; charset=utf-8'<span>);
</span>?>




    <meta charset="UTF-8">
    <title>verification code</title>
    <link rel="stylesheet" type="text/css" href="style/basic.css">



    <div>
        <form method="post" name="verification" action="verification-code.php?action=verification">
            dl>
                <dd>验证码:<input type="text" name="code">class="code" /><img  src="codeimg.php" alt="php实现动态随机验证码机制(CAPTCHA)" >
</dd>
                <dd>
<input type="submit">class="submit" value="验证" /></dd>
            <span>dl</span>>
        </form>
    </div>


登录后复制

显示如下:

2)创建产生验证码页面

创建codeimg.php为verification-code.php html代码里的img提供验证码图片

首先必须在codeimg.php页面开启session;

其次,将我们封装好的global.func.php全局函数库引入进来;

最后,运行_code();

<span>php 
</span><span>/*</span><span>*
 *      [verification-code] (C)2015-2100 jingwhale.
 *      
 *      This is a freeware
 *      $Id: codeimg.php 2015-02-05 20:53:56 jingwhale$
 </span><span>*/</span>

<span>//</span><span>开启session</span>
<span>session_start</span><span>();

</span><span>//</span><span>引入全局函数库(自定义)</span>
<span>require</span> <span>dirname</span>(<span>__FILE__</span>).'/includes/global.func.php'<span>;

</span><span>//</span><span>运行验证码函数。通过数据库的_code方法,设置验证码的各种属性,生成图片</span>
_code(125,25,6,<span>false</span><span>);

</span>?>
登录后复制

3)创建session检验机制

首先必须在verification-code.php页面开启session;

其次,设计提交验证码的方式,本文以get方式提交,当action=verification时提交成功;

最后,创建验证函数,原理是将客户端用户提交的验证码同服务器codeimg.php中session的验证码是否一致;这里有一个js弹窗函数_alert_back(),我们也把它封装在global.func.php里;

修改verification-code.php中php代码如下:

<span>php 
</span><span>/*</span><span>*
 *      [verification-code] (C)2015-2100 jingwhale.
 *
 *      This is a freeware
 *      $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$
 </span><span>*/</span>

<span>//</span><span>设置字符集编码</span>
<span>header</span>('Content-Type: text/html; charset=utf-8'<span>);

</span><span>//</span><span>开启session</span>
<span>session_start</span><span>();

</span><span>//</span><span>引入全局函数库(自定义)</span>
<span>require</span> <span>dirname</span>(<span>__FILE__</span>).'/includes/global.func.php'<span>;

</span><span>//</span><span>检验验证码</span>
<span>if</span> (<span>$_GET</span>['action'] == 'verification'<span>) {
    
    </span><span>if</span> (!(<span>$_POST</span>['code'] == <span>$_SESSION</span>['code'<span>])) {
        _alert_back(</span>'验证码不正确!'<span>);
    }</span><span>else</span><span>{
        _alert_back(</span>'验证码通过!'<span>);
    }
}  
</span>?>




    <meta charset="UTF-8">
    <title>verification code</title>
    <link rel="stylesheet" type="text/css" href="style/basic.css">
    <script type="text/javascript" src="js/codeimg.js"></script>



    <div>
        <form method="post" name="verification" action="verification-code.php?action=verification">
            dl>
                <dd>验证码:<input type="text" name="code">class="code" /><img  src="codeimg.php" alt="php实现动态随机验证码机制(CAPTCHA)" >
</dd>
                <dd>
<input type="submit">class="submit" value="验证" /></dd>
            <span>dl</span>>
        </form>
    </div>


登录后复制

3.实现点击验证码图片更新验证码

上面若想实现验证码更新,必须刷新页面;我们写一个codeimg.js函数实现点击验证码图片更新验证码

window.onload = <span>function</span><span> () {
    </span><span>var</span> code = document.getElementById('codeimg');<span>//</span><span>通过id找到html中img标签</span>
    code.onclick = <span>function</span> () {<span>//</span><span>为标签添加点击事件</span>
        <span>this</span>.src='codeimg.php?tm='+Math.random();<span>//</span><span>修改时间,重新指向codeimg.php</span>
<span>    };    
}</span>
登录后复制

然后在verification-code.php html代码head里它即可。

欢迎转载。转载请注明转载字样,标注原作者和原博文地址。

以上就介绍了php实现动态随机验证码机制(CAPTCHA),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!