php制作动态随机验证码


Posted in PHP onFebruary 12, 2015

验证码(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_size 和 y_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 中从坐标 x1,y1 到 x2,y2(图像左上角为 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 所代表的图像的 x,y 坐标处(这是字符串左上角坐标,整幅图像的左上角为 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)调用创建的图形

<img src="Demo4.php" alt="PHP创建的图片" />

示例代码如下:

<?php

    //第一步,设置文件MIME类型

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

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

    $im = imagecreatetruecolor(200,200);

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

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

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

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

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

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

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

    imagestring($im,5,66,20,'Jing.Whale',$white);

    //第五步,输出最终图形

    imagepng($im);

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

    imagedestroy($im);    

?>

显示效果:

php制作动态随机验证码

二.创建动态验证码

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

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

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

1)创建随机码
  

for ($i=0;$i<$_rnd_code;$i++) {

        $_nmsg .= dechex(mt_rand(0,15));

    }

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

2)保存在session
 

$_SESSION['code'] = $_nms

3)创建图片

//创建一张图像

$_img = imagecreatetruecolor($_width,$_height);

//白色

$_white = imagecolorallocate($_img,255,255,255);

//填充

imagefill($_img,0,0,$_white);

if ($_flag) {

//黑色,边框

    $_black = imagecolorallocate($_img,0,0,0);

    imagerectangle($_img,0,0,$_width-1,$_height-1,$_black);

}

4)模糊背景

//随机画出6个线条

for ($i=0;$i<6;$i++) {

   $_rnd_color = imagecolorallocate($_img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));

   imageline($_img,mt_rand(0,$_width),mt_rand(0,$_height),mt_rand(0,$_width),mt_rand(0,$_height),$_rnd_color);

   }

//随机雪花

for ($i=0;$i<100;$i++) {

   $_rnd_color = imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));

   imagestring($_img,1,mt_rand(1,$_width),mt_rand(1,$_height),'*',$_rnd_color);

   }

5)输出及销毁

//输出验证码

for ($i=0;$i<strlen($_SESSION['code']);$i++) {

        $_rnd_color = imagecolorallocate($_img,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));

        imagestring($_img,5,$i*$_width/$_rnd_code+mt_rand(1,10),mt_rand(1,$_height/2),$_SESSION['code'][$i],$_rnd_color);

    }

//输出图像

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

imagepng($_img);

//销毁

imagedestroy($_img);

将其封装在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无边框(默认)

封装后的代码如下:

<?php 

/**

 *      [verification-code] (C)2015-2100 jingwhale.

 *      

 *      This is a freeware

 *      $Id: global.func.php 2015-02-05 20:53:56 jingwhale$

 */

/**

 * _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 这个函数执行后产生一个验证码

 */

function _code($_width = 75,$_height = 25,$_rnd_code = 4,$_flag = false) {

    //创建随机码

    for ($i=0;$i<$_rnd_code;$i++) {

        $_nmsg .= dechex(mt_rand(0,15));

    }

    //保存在session

    $_SESSION['code'] = $_nmsg;

    //创建一张图像

    $_img = imagecreatetruecolor($_width,$_height);

    //白色

    $_white = imagecolorallocate($_img,255,255,255);

    //填充

    imagefill($_img,0,0,$_white);

    if ($_flag) {

        //黑色,边框

        $_black = imagecolorallocate($_img,0,0,0);

        imagerectangle($_img,0,0,$_width-1,$_height-1,$_black);

    }

    //随即画出6个线条

    for ($i=0;$i<6;$i++) {

        $_rnd_color = imagecolorallocate($_img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));

        imageline($_img,mt_rand(0,$_width),mt_rand(0,$_height),mt_rand(0,$_width),mt_rand(0,$_height),$_rnd_color);

    }

    //随即雪花

    for ($i=0;$i<100;$i++) {

        $_rnd_color = imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));

        imagestring($_img,1,mt_rand(1,$_width),mt_rand(1,$_height),'*',$_rnd_color);

    }

    //输出验证码

    for ($i=0;$i<strlen($_SESSION['code']);$i++) {

        $_rnd_color = imagecolorallocate($_img,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));

        imagestring($_img,5,$i*$_width/$_rnd_code+mt_rand(1,10),mt_rand(1,$_height/2),$_SESSION['code'][$i],$_rnd_color);

    }

    //输出图像

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

    imagepng($_img);

    //销毁

    imagedestroy($_img);

}

?>

2.创建验证机制

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

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

<?php 

/**

 *      [verification-code] (C)2015-2100 jingwhale.

 *

 *      This is a freeware

 *      $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$

 */

//设置字符集编码

header('Content-Type: text/html; charset=utf-8');

?>

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>verification code</title>

    <link rel="stylesheet" type="text/css" href="style/basic.css" />

</head>

<body>

    <div id="testcode">

        <form method="post" name="verification" action="verification-code.php?action=verification">

            <dl>

                <dd>验证码:<input type="text" name="code" class="code" /><img src="codeimg.php" id="codeimg"  /></dd>

                <dd><input type="submit" class="submit" value="验证" /></dd>

            </dl>

        </form>

    </div>

</body>

</html>

显示如下:

php制作动态随机验证码

2)创建产生验证码图片页面

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

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

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

最后,运行_code();

<?php 

/**

 *      [verification-code] (C)2015-2100 jingwhale.

 *      

 *      This is a freeware

 *      $Id: codeimg.php 2015-02-05 20:53:56 jingwhale$

 */

//开启session

session_start();

//引入全局函数库(自定义)

require dirname(__FILE__).'/includes/global.func.php';

//运行验证码函数。通过数据库的_code方法,设置验证码的各种属性,生成图片

_code(125,25,6,false);

?>

php制作动态随机验证码

3)创建session检验机制

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

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

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

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

<?php 

/**

 *      [verification-code] (C)2015-2100 jingwhale.

 *

 *      This is a freeware

 *      $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$

 */

//设置字符集编码

header('Content-Type: text/html; charset=utf-8');

//开启session

session_start();

//引入全局函数库(自定义)

require dirname(__FILE__).'/includes/global.func.php';

//检验验证码

if ($_GET['action'] == 'verification') {

    if (!($_POST['code'] == $_SESSION['code'])) {

        _alert_back('验证码不正确!');

    }else{

        _alert_back('验证码通过!');

    }

}  

?>

<!DOCTYPE html>

<html>

<head>

    <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>

</head>

<body>

    <div id="testcode">

        <form method="post" name="verification" action="verification-code.php?action=verification">

            <dl>

                <dd>验证码:<input type="text" name="code" class="code" /><img src="codeimg.php" id="codeimg"  /></dd>

                <dd><input type="submit" class="submit" value="验证" /></dd>

            </dl>

        </form>

    </div>

</body>

</html>

php制作动态随机验证码

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

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

window.onload = function () {

    var code = document.getElementById('codeimg');//通过id找到html中img标签

    code.onclick = function () {//为标签添加点击事件

        this.src='codeimg.php?tm='+Math.random();//修改时间,重新指向codeimg.php

    };    

}

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

php制作动态随机验证码

PHP 相关文章推荐
PHP 编写的 25个游戏脚本
May 11 PHP
php在页面中调用fckeditor编辑器的方法
Jun 10 PHP
php 无法加载mcrypt.dll的解决办法
Apr 03 PHP
php 无限级分类,超级简单的无限级分类,支持输出树状图
Jun 29 PHP
10个超级有用值得收藏的PHP代码片段
Jan 22 PHP
PHP根据图片色界在不同位置加水印的方法
Jul 01 PHP
PHP中常见的缓存技术实例分析
Sep 23 PHP
Zend Framework教程之资源(Resources)用法实例详解
Mar 14 PHP
php json_encode与json_decode详解及实例
Dec 13 PHP
PHP去除字符串最后一个字符的三种方法实例
Mar 01 PHP
PHP数组实际占用内存大小原理解析
Dec 11 PHP
详解PHP设计模式之依赖注入模式
May 25 PHP
PHP获取一年中每个星期的开始和结束日期的方法
Feb 12 #PHP
php模拟post提交数据的方法
Feb 12 #PHP
PHP遍历数组的三种方法及效率对比分析
Feb 12 #PHP
PHP进程同步代码实例
Feb 12 #PHP
PHP CURL 内存泄露问题解决方法
Feb 12 #PHP
PHP中捕获超时事件的方法实例
Feb 12 #PHP
php单例模式示例分享
Feb 12 #PHP
You might like
PHP常用技术文之文件操作和目录操作总结
2014/09/27 PHP
php使用fputcsv()函数csv文件读写数据的方法
2015/01/06 PHP
php程序内部post数据的方法
2015/03/31 PHP
利用php实现一周之内自动登录存储机制(cookie、session、localStorage)
2016/10/31 PHP
Javascript笔记一 js以及json基础使用说明
2010/05/22 Javascript
SlideView 图片滑动(扩展/收缩)展示效果
2010/08/01 Javascript
jQuery.autocomplete 支持中文输入(firefox)修正方法
2011/03/10 Javascript
JavaScript中的操作符==与===介绍
2014/12/31 Javascript
jQuery操作基本控件方法实例分析
2015/12/31 Javascript
Node.js开发者必须了解的4个JS要点
2016/02/21 Javascript
JS中this上下文对象使用方式
2016/10/09 Javascript
KnockoutJS 3.X API 第四章之事件event绑定
2016/10/10 Javascript
js读取json文件片段中的数据实例
2017/03/09 Javascript
jQuery插件HighCharts实现的2D堆条状图效果示例【附demo源码下载】
2017/03/14 Javascript
JS实现二叉查找树的建立以及一些遍历方法实现
2017/04/17 Javascript
xmlplus组件设计系列之网格(DataGrid)(10)
2017/05/05 Javascript
webpack打包后直接访问页面图片路径错误的解决方法
2017/06/17 Javascript
JS实现前端页面的搜索功能
2018/06/12 Javascript
fetch 如何实现请求数据
2018/12/20 Javascript
判断js数据类型的函数实例详解
2019/05/23 Javascript
jQuery实现移动端图片上传预览组件的方法分析
2020/05/01 jQuery
python抓取最新博客内容并生成Rss
2015/05/17 Python
Python OpenCV实现图片上输出中文
2018/01/22 Python
Sanic框架Cookies操作示例
2018/07/17 Python
Python交互式图形编程的实现
2019/07/25 Python
Python3搭建http服务器的实现代码
2020/02/11 Python
Python基于pyecharts实现关联图绘制
2020/03/27 Python
一文详述 Python 中的 property 语法
2020/09/01 Python
浅谈css3新单位vw、vh、vmin、vmax的使用详解
2017/12/01 HTML / CSS
Oakley西班牙官方商店:太阳眼镜和男女运动服
2019/04/26 全球购物
旷课检讨书1000字
2014/02/14 职场文书
优秀实习生主要事迹
2014/05/29 职场文书
党的群众路线个人对照检查材料
2014/09/23 职场文书
幼儿园开学温馨提示
2015/07/15 职场文书
如何理解Vue简单状态管理之store模式
2021/05/15 Vue.js
springboot为异步任务规划自定义线程池的实现
2022/06/14 Java/Android