Home >Backend Development >PHP Tutorial >PHP implements dynamic random verification code mechanism (CAPTCHA)
CAPTCHA is the abbreviation of "Completely Automated Public Turing test to tell Computers and Humans Apart". It is a public fully automated program that distinguishes whether the user is a computer or a human. It can prevent: malicious cracking of passwords, ticket fraud, forum flooding, and effectively prevents a hacker from using a specific program to violently crack a specific registered user from making continuous login attempts. In fact, using verification codes is a common method for many websites now. We use This function is implemented in a relatively simple way.
This question can be generated and judged by a computer, but only a human can answer it. Since computers cannot answer CAPTCHA questions, the user who answers the questions can be considered a human.
PHP production dynamic verification code is based on PHP image processing. Let's first introduce the image processing of PHP.Introduction to .php image processing
Generally generated graphics are stored in PHP's document format, but dynamic graphics can be directly obtained through HTML's image insertion method SRC. For example, verification code, watermark, thumbnail, etc.
General process for creating images:
1). Set the header to tell the browser the MIME type you want to generate.The first step is to set the file MIME type and output type. Change the output type to image stream2). Create an image area, and all subsequent operations will be based on this image area.
3).Draw a filled background in the blank image area.
4). Draw graphic outlines on the background to enter text.
5).Output the final graphics.
6). Clear all resources.
7). Call images from other pages.
header('Content-Type: image/png;');Generally generated images can be png, jpeg, gif, wbmp
The second step is to create a graphics area and image background
imagecreatetruecolor() returns an image identifier representing a black image of size x_size and
y_size.
Syntax: resource imagecreatetruecolor ( int $width , int
$height )
$im = imagecreatetruecolor(200,200);The third step is to draw a filled background in the blank image area
Requires a color filler; imagecolorallocate -- assigns a color to an image; Syntax: int imagecolorallocate ( resource $image , int
$red , int
$green , int
$blue )
$blue = imagecolorallocate($im,0,102,255);
Fill this blue color into the background; imagefill -- area filling; Syntax: bool imagefill ( resource $image , int
$x , int
$y , int
$color )
imagefill($im,0,0,$blue);The fourth step is to enter some lines, text, etc. on the blue background
Color Filler
$white = imagecolorallocate($im,255,255,255);Draw two line segments: imageline
imageline() draws a line segment in the image image using the
color color from coordinates
x1,
y1 to
x2,
y2 (the upper left corner of the image is 0, 0).
Syntax: bool imageline ( resource $image , int
$x1 , int
$y1 , int
$x2 , int
$y2 , int
$color )
imageline($im,0,0,200,200,$white);Draw a line of string horizontally: imagestringimageline($im,200,0,0,200,$white);
imagestring() uses col color to draw the string
s to the
x,
y coordinates of the image represented by
image (this is the coordinate of the upper left corner of the string, the upper left corner of the entire image is 0,0). If
font is 1, 2, 3, 4 or 5, the built-in font is used.
Syntax: bool imagestring ( resource $image , int
$font , int
$x , int
$y , string
$s , int
$col )
imagestring($im,5,66,20,'jingwhale',$white);
imagepng() Outputs a GD image stream (image
) in PNG format to standard output (usually a browser), or to a file if a filename is given with filename
. Syntax: bool imagepng ( resource $image
[, string $filename
] )
imagepng($im);
imagedestroy() frees the memory associated with image
. Syntax: bool imagedestroy ( resource $image
)
imagedestroy($im);
The sample code is as follows:
<?<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>?>
Display effect:
Attached: Code source addresshttps://github.com/cnblogs-/php-captcha
The random code uses hexadecimal; the blurred background means adding lines, snowflakes, etc. to the background of the picture.
1) Create random code
<span>for</span> (<span>$i</span>=0;<span>$i</span><<span>$_rnd_code</span>;<span>$i</span>++<span>) { </span><span>$_nmsg</span> .= <span>dechex</span>(<span>mt_rand</span>(0,15<span>)); }</span>
string dechex (int $number
), returns a string containing the hexadecimal representation of the given number
parameter.
2) Save in session
<span>$_SESSION</span>['code'] = <span>$_nms</span>
3)Create pictures
<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) Blur background
<span>//</span><span>随即画出6个线条</span> <span>for</span> (<span>$i</span>=0;<span>$i</span><6;<span>$i</span>++<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><100;<span>$i</span>++<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) Output and destruction
<span>//</span><span>输出验证码</span> <span>for</span> (<span>$i</span>=0;<span>$i</span><<span>strlen</span>(<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>);
Encapsulate it in the global.func.php global function library, and the function name is _code() for easy calling. We will set the four parameters $_width, $_height, $_rnd_code, $_flag to enhance the flexibility of the function.
* @param int $_width The length of the verification code: if you want 6 digits, 75+50 is recommended; if you want 8 digits, 75+50+50 is recommended, and so on
* @param int $_height The height of the verification code
* @ param int $_rnd_code The number of digits in the verification code
* @param bool $_flag Whether the verification code requires a border: true with border, false without border (default)
The encapsulated code is as follows:
<?<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><<span>$_rnd_code</span>;<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><6;<span>$i</span>++<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><100;<span>$i</span>++<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><<span>strlen</span>(<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>?>
Create a PHP verification page and check whether the verification code is consistent through session.
1) Create verification-code.php verification page
<?<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>?> <!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> <form method="post" name="verification" action="verification-code.php?action=verification"> <<span>dl</span>> <dd>验证码:<input type="text" name="code" <span>class</span>="code" /><img src="codeimg.php" /></dd> <dd><input type="submit" <span>class</span>="submit" value="验证" /></dd> </<span>dl</span>> </form> </div> </body> </html>
Displayed as follows:
2) Create a page to generate verification code
Create codeimg.php to provide verification code images for img in verification-code.php html code
First you must open the session on the codeimg.php page;
Secondly, introduce our encapsulated global.func.php global function library;
Finally, run_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) Create session verification mechanism
First, you must open the session on the verification-code.php page;
Secondly, design the way to submit the verification code. This article is submitted in the get method. When action=verification, the submission is successful;
Finally, create a verification function. The principle is to check whether the verification code submitted by the client user is consistent with the verification code of the session in the server codeimg.php; there is a js pop-up function _alert_back(), and we also encapsulate it in global. in func.php;
Modify the php code in verification-code.php as follows:
<?<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>?> <!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> <form method="post" name="verification" action="verification-code.php?action=verification"> <<span>dl</span>> <dd>验证码:<input type="text" name="code" <span>class</span>="code" /><img src="codeimg.php" /></dd> <dd><input type="submit" <span>class</span>="submit" value="验证" /></dd> </<span>dl</span>> </form> </div> </body> </html>
If you want to update the verification code above, you must refresh the page; we write a codeimg.js function to update the verification code by clicking on the verification code image
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>
Then it in the verification-code.php html code head.
End
Reprinting is welcome. When reprinting, please indicate the word reprint, the original author and the original blog post address.
The above introduces the implementation of dynamic random verification code mechanism (CAPTCHA) in PHP, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.