PHP production dynamic random verification Code _php instance

Source: Internet
Author: User
Tags image identifier
The Verification Code (CAPTCHA) is the abbreviation for "Completely Automated public Turing test to tell Computers and humans Apart" (fully automated computer-and human-Turing test), is a public automatic program that distinguishes whether a user is a computer or a person. Can prevent: Malicious hack password, brush tickets, forum irrigation, effectively prevent a hacker to a particular registered users with a specific program brute force to make a continuous attempt to break the way, in fact, with the verification code is now a lot of web site way, we use a relatively simple way to achieve this function.

This problem can be generated and judged by a computer, but only humans can answer it. Since the computer is unable to answer the CAPTCHA question, the user who answers the question can be considered human.

PHP Production dynamic Verification code is based on PHP image processing, the following first introduce PHP image processing.

I. Introduction to PHP image processing

In PHP5, the processing of dynamic images is much easier than it used to be. PHP5 the GD expansion pack in the php.ini file, you can use it just by removing the appropriate annotations for the GD expansion pack. PHP5 contains the GD library that is the upgraded GD2 library, which contains some useful JPG features that support true color image processing.

Generally generated graphics, stored in PHP document format, but can be used in the HTML image insertion method src to directly get dynamic graphics. For example, verification code, watermark, thumbnail, and so on.

General process for creating images:

1). Set the header to tell the browser which MIME type you want to generate.

2). Create an image area that will be based on this image area in future operations.

3). Draws the fill background in the blank image area.

4). Draw a graphic outline into the background to enter text.

5). Output the final graphic.

6). Clear all resources.

7). Other pages call the image.

The first step is to set the file MIME type, and the output type to change the output type to the image stream

Copy the Code code as follows:
Header (' content-type:image/png; ');

The normally generated image can be png,jpeg,gif,wbmp

Second step, create a graphics area, image background

Imagecreatetruecolor () returns an image identifier representing a black image with a size of x_size and y_size. Syntax: Resource imagecreatetruecolor (int $width, int $height)

Copy the Code code as follows:
$im = Imagecreatetruecolor (200,200);

Third step, draw the fill background in the blank image area

To have a color filler; imagecolorallocate-assigns a color to an image; syntax: int imagecolorallocate (resource $image, int $red, int $green, int $blue)

Copy the Code code as follows:
$blue = Imagecolorallocate ($im, 0,102,255);

Fill the blue color to the background; Imagefill-area fill; Syntax: bool Imagefill (Resource $image, int $x, int $y, int $color)

Copy the Code code as follows:
Imagefill ($im, 0,0, $blue);

Fourth step, enter some lines, text, etc. on the blue background

Color Filler

Copy the Code code as follows:
$white = Imagecolorallocate ($im, 255,255,255);

Draw two line segments: Imageline

Imageline () Draws a line segment from coordinates x1,y1 to X2,y2 (0, 0 in the upper left corner of the image) with a color color. Syntax: BOOL Imageline (Resource $image, int $x 1, int $y 1, int $x 2, int $y 2, int $color)

Copy the Code code as follows:
Imageline ($im, 0,0,200,200, $white);
Imageline ($im, 200,0,0,200, $white);

Draw a line of string horizontally: imagestring

Imagestring () uses the Col color to draw the string s to the x, y coordinates of the image represented by image (this is the upper-left coordinate of the string, and the upper-left corner of the entire image is 0,0). If the 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)

Copy the Code code as follows:
Imagestring ($im, 5,66,20, ' Jingwhale ', $white);

Fifth step, output final graphics

Imagepng () Exports the GD image Stream (image) to the standard output (usually a browser) in PNG format, or outputs it to the file if it is given a filename with filename. Syntax: BOOL Imagepng (Resource $image [, String $filename])

Copy the Code code as follows:
Imagepng ($im);

Sixth step, I'm going to empty all the resources.

Imagedestroy () releases the memory associated with the image. Syntax: BOOL Imagedestroy (Resource $image)

Copy the Code code as follows:
Imagedestroy ($im);

Other pages (HTML) call the created graphic

Copy the Code code as follows:

The sample code is as follows:

Copy the Code code as follows:
<?php
The first step is to set the file MIME type
Header (' content-type:image/png; ');
Second step, create a graphics area, image background
$im = Imagecreatetruecolor (200,200);
Third step, draw the fill background in the blank image area
$blue = Imagecolorallocate ($im, 0,102,255);
Imagefill ($im, 0,0, $blue);
Fourth step, enter some lines, text, etc. on the blue background
$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);
Fifth step, output final graphics
Imagepng ($im);
Sixth step, I'm going to empty all the resources.
Imagedestroy ($im);
?>

Display effect:

Two. Create a dynamic verification code

Attached: Code Source Address Https://github.com/cnblogs-/php-captcha

1. Create a picture with a verification code and blur the background

The random code uses 16 binary, the blurred background is in the picture background to add the line, the snowflake and so on.

1) Create random code

Copy the Code code as follows:
for ($i =0; $i <$_rnd_code; $i + +) {
$_nmsg. = Dechex (Mt_rand (0,15));
}
String Dechex (int) that returns a string containing the hexadecimal representation of the given number parameter.

2) Save in session

Copy the Code code as follows:
$_session[' Code ' = $_nms

3) Create a picture

Copy the Code code as follows:
Create an image
$_img = Imagecreatetruecolor ($_width,$_height);
White
$_white = Imagecolorallocate ($_img,255,255,255);
Fill
Imagefill ($_img,0,0,$_white);
if ($_flag) {
Black, border
$_black = Imagecolorallocate ($_img,0,0,0);
Imagerectangle ($_img,0,0,$_width-1,$_height-1,$_black);
}

4) Blur background

Copy the Code code as follows:
Randomly draw 6 lines
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);
}
Random Snowflakes
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) Output and destruction

Copy the Code code as follows:
Output Verification Code
for ($i =0; $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);
}
Output image
Header (' content-type:image/png ');
Imagepng ($_IMG);
Destroyed
Imagedestroy ($_IMG);

It is encapsulated in the global.func.php global function library, and the function name is _code () for invocation. We will set $_width, $_height, $_rnd_code,$_flag four parameters to enhance the flexibility of the function.

* @param int $_width The length of the verification code: if you want to 6-bit length recommended 75+50, if you want 8-bit, recommend 75+50+50, and so on
* @param int $_height The height of the verification code
* @param int $_rnd_code The number of digits of the verification code
* @param bool $_flag Verification code requires a border: True has a border, false no border (default)

The code after encapsulation is as follows:

Copy CodeThe code is as follows:
<?php
/**
* [Verification-code] (C) 2015-2100 Jingwhale.
*
* This is a freeware
* $Id: global.func.php 2015-02-05 20:53:56 jingwhale$
*/
/**
* _code () is a CAPTCHA function
* @access Public
* @param int $_width The length of the verification code: if you want to 6-bit length recommended 75+50, if you want 8-bit, recommend 75+50+50, and so on
* @param int $_height The height of the verification code
* @param int $_rnd_code The number of digits of the verification code
* @param bool $_flag Verification code requires a border: True has a border, false no border (default)
* @return void A verification code is generated after this function is executed
*/
function _code ($_width = 75,$_height = 25,$_rnd_code = 4,$_flag = False) {
Create Random Code
for ($i =0; $i <$_rnd_code; $i + +) {
$_nmsg. = Dechex (Mt_rand (0,15));
}
Save in session
$_session[' Code ' = $_nmsg;
Create an image
$_img = Imagecreatetruecolor ($_width,$_height);
White
$_white = Imagecolorallocate ($_img,255,255,255);
Fill
Imagefill ($_img,0,0,$_white);
if ($_flag) {
Black, border
$_black = Imagecolorallocate ($_img,0,0,0);
Imagerectangle ($_img,0,0,$_width-1,$_height-1,$_black);
}
6 lines are drawn immediately
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);
}
Immediately snowflakes
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);
}
Output Verification Code
for ($i =0; $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);
}
Output image
Header (' content-type:image/png ');
Imagepng ($_IMG);
Destroyed
Imagedestroy ($_IMG);
}
?>

2. Create a validation mechanism

Create a PHP Verification page to verify that the verification code is consistent through the session.

1) Create verification-code.php Verification page

Copy the Code code as follows:
<?php
/**
* [Verification-code] (C) 2015-2100 Jingwhale.
*
* This is a freeware
* $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$
*/
Setting Character Set encoding
Header (' content-type:text/html; Charset=utf-8 ');
?>




Verification Code








Shown below:

2) Create a picture page that generates a CAPTCHA

Create codeimg.php to provide CAPTCHA images for IMG in verification-code.php HTML code

The session must first be opened on the codeimg.php page;

Secondly, we introduced the global.func.php global function library which we encapsulated;

Finally, run _code ();

Copy the Code code as follows:
<?php
/**
* [Verification-code] (C) 2015-2100 Jingwhale.
*
* This is a freeware
* $Id: codeimg.php 2015-02-05 20:53:56 jingwhale$
*/
Open session
Session_Start ();
Introducing the Global function library (custom)
Require DirName (__file__). ' /includes/global.func.php ';
Run the CAPTCHA function. Through the _code method of the database, set the various properties of the verification code, generate the picture
_code (125,25,6,false);
?>

3) Create session inspection mechanism

First, you must also open the session on the verification-code.php page;

Secondly, design the way of submitting verification code, this article is submitted by Get method, when Action=verification is submitted successfully;

Finally, to create a validation function, the principle is that the client user submits the verification code and the server codeimg.php the session verification code is consistent; here is a JS pop-up function _alert_back (), we also encapsulate it in global.func.php;

Modify the PHP code in verification-code.php as follows:

Copy the Code code as follows:
<?php
/**
* [Verification-code] (C) 2015-2100 Jingwhale.
*
* This is a freeware
* $Id: verification-code.php 2015-02-05 20:53:56 jingwhale$
*/
Setting Character Set encoding
Header (' content-type:text/html; Charset=utf-8 ');
Open session
Session_Start ();
Introducing the Global function library (custom)
Require DirName (__file__). ' /includes/global.func.php ';
Inspection Verification Code
if ($_get[' action '] = = ' verification ') {
if (! ( $_post[' code '] = = $_session[' code ')) {
_alert_back (' Verification code is incorrect! ');
}else{
_alert_back (' Verification code passed! ');
}
}
?>




Verification Code









3. Implement click Verification Code image Update Verification code

If you want to implement verification code update, you must refresh the page; we write a codeimg.js function to implement click Verification Code image Update Verification code

Copy the Code code as follows:
Window.onload = function () {
var code = document.getElementById (' codeimg ');//Find an IMG tag in HTML by ID
Code.onclick = function () {//Add click event for label
This.src= ' codeimg.php?tm= ' +math.random ();//modify time, point back to codeimg.php
};
}

Then it can be in the verification-code.php HTML code head .

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.