PHP to make dynamic random verification code _php instance

Source: Internet
Author: User
Tags image identifier pack strlen

The authentication Code (CAPTCHA) is the abbreviation for "completely automated public Turing test to tell Computers and humans Apart" (fully automatic distinguishing between computer and human Turing tests), It is a public automatic program that distinguishes the user from the computer or the person. Can prevent: Malicious crack password, brush ticket, forum irrigation, effectively prevent a hacker to a specific registered user with a specific program of brute force to break the way of the landing attempt, in fact, with the verification code is now a lot of Web site, we use a relatively simple way to achieve this function.

This problem can be generated and judged by the computer, but it must be solved only by humans. Because the computer cannot answer the CAPTCHA problem, the user who answers the question can be considered human.

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

A brief introduction to PHP image processing

In PHP5, dynamic image processing is much easier than it used to be. PHP5 in the php.ini file contains the GD expansion pack, just remove the corresponding comments from the GD expansion pack can be used normally. PHP5 contains the GD library, which is the upgraded GD2 library, which contains some useful JPG features that support true color image processing.

Generally generated graphics, through the document format of PHP storage, but can be through the HTML image Insert way SRC to directly obtain dynamic graphics. For example, verification code, watermark, miniature map and so on.

General process for creating images:

1. Set the header to tell the browser what type of mime you want to generate.

2. Create an image area that will be based on this image area later.

3. Draws a fill background in a blank image area.

4. Draw a graphic outline on the background to enter text.

5). Output final graphics.

6). Clear all resources.

7). Other pages call the image.

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

Copy Code code as follows:

Header (' content-type:image/png; ');

Generally generated images can be png,jpeg,gif,wbmp

The second step is to create a graphics area with an image background

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

Copy Code code as follows:

$im = Imagecreatetruecolor (200,200);

Step three, draw the fill background in the blank image area

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

Copy Code code as follows:

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

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

Copy Code code as follows:

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

Step fourth, enter some lines, text, etc. on the blue background.

Color Filler

Copy Code code as follows:

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

Draw two line segments: Imageline

Imageline () Draws a line segment from the coordinate x1,y1 to the x2,y2 (0, 0) in image images in color color. Syntax: BOOL Imageline (Resource $image, int $x 1, int $y 1, int $x 2, int $y 2, int $color)

Copy Code code as follows:

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

Horizontally draw a line of strings: imagestring

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

Copy Code code as follows:

Imagestring ($im, 5,66,20, ' Jingwhale ', $white);

Fifth step, output final graphics

Imagepng () outputs the GD image Stream (image) to the standard output (typically 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 Code code as follows:

Imagepng ($im);

Step sixth, I'm going to clear all the resources.

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

Copy Code code as follows:

Imagedestroy ($im);

Graphics created by other page (HTML) calls

Copy Code code as follows:


The sample code is as follows:

Copy Code code as follows:

<?php
The first step is to set the file MIME type
Header (' content-type:image/png; ');
The second step is to create a graphics area with an image background
$im = Imagecreatetruecolor (200,200);
Step three, draw the fill background in the blank image area
$blue = Imagecolorallocate ($im, 0,102,255);
Imagefill ($im, 0,0, $blue);
Step fourth, 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);
Step sixth, I'm going to clear all the resources.
Imagedestroy ($im);
?>

Display effect:

Two. Create dynamic verification Code

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

1. Create a picture with a captcha and blur the background

Random code using 16, fuzzy background is in the picture background plus lines, snowflakes and so on.

1) Create random code

Copy Code code as follows:

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

2) Save in session

Copy Code code as follows:

$_session[' code '] = $_nms

3) Create a picture

Copy Code code as follows:

Create a picture
$_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) Fuzzy background

Copy 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 Code code as follows:

Output Verification Code
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);
}
Output image
Header (' content-type:image/png ');
Imagepng ($_IMG);
Destroyed
Imagedestroy ($_IMG);

Encapsulated in the global.func.php global function library, the function name is _code () to invoke. 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 6-bit length recommended 75+50; If you want 8 digits, recommend 75+50+50, and so on.
* @param the height of the int $_height verification code
* @param int $_rnd_code Verification code number of digits
* @param bool $_flag Verify code requires a border: True has a border, false no border (default)

The encapsulated code is as follows:

Copy Code code 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 validation code function
* @access Public
* @param int $_width The length of the verification code: if you want 6-bit length recommended 75+50; If you want 8 digits, recommend 75+50+50, and so on.
* @param the height of the int $_height verification code
* @param int $_rnd_code Verification code number of digits
* @param bool $_flag Verify code requires a border: True has a border, false no border (default)
* @return void This function is executed to produce a verification code
*/
function _code ($_width = 75,$_height = 25,$_rnd_code = 4,$_flag = False) {
Create a random code
For ($i =0 $i <$_rnd_code; $i + +) {
$_nmsg. = Dechex (Mt_rand (0,15));
}
Save in session
$_session[' code '] = $_nmsg;
Create a picture
$_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);
}
Then 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);
}
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 <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);
}
Output image
Header (' content-type:image/png ');
Imagepng ($_IMG);
Destroyed
Imagedestroy ($_IMG);
}
?>

2. Create a validation mechanism

Create the PHP validation page, and verify that the code is consistent by session.

1) Create verification-code.php Verification page

Copy 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$
*/
Set Character Set encoding
Header (' content-type:text/html; Charset=utf-8 ');
?>
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>verification code</title>
<link rel= "stylesheet" type= "Text/css" href= "Style/basic.css"/>
<body>
<div id= "Testcode" >
<form method= "POST" name= "verification" action= "Verification-code.php?action=verification" >
<dl>
<dd> Verification Code: <input type= "text" name= "code" class= "code"/></dd >
<dd><input type= "Submit" class= "Submit" value= "Validation"/></dd>
</dl>
</form>
</div>
</body>

The display is as follows:

2 Create the Validation code picture page

Create a codeimg.php for the IMG in the verification-code.php HTML code to provide a CAPTCHA picture

First, the session must be opened on the codeimg.php page.

Secondly, we introduce the global.func.php global function library which we encapsulate well.

Finally, run _code ();

Copy 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 Global function libraries (custom)
Require DirName (__file__). ' /includes/global.func.php ';
Run the validation code 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 of all must be on the Verification-code.php page also open session;

Secondly, the design of the way to submit the verification code, this article to get the way to submit, when Action=verification submitted successfully;

Finally, you create a validation function that is consistent with the validation code that the client user submits to the session in the server codeimg.php; here is a JS window function _alert_back (), we also encapsulate it in global.func.php;

To modify verification-code.php, the PHP code is as follows:

Copy 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$
*/
Set Character Set encoding
Header (' content-type:text/html; Charset=utf-8 ');
Open session
Session_Start ();
Introducing Global function libraries (custom)
Require DirName (__file__). ' /includes/global.func.php ';
Verification Code
if ($_get[' action '] = = ' verification ') {
if (!) ( $_post[' code '] = = $_session[' Code ']) {
_alert_back (' Verification code not correct! ');
}else{
_alert_back (' Verification code passed! ');
}
}
?>
<! DOCTYPE html>
<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>
<body>
<div id= "Testcode" >
<form method= "POST" name= "verification" action= "Verification-code.php?action=verification" >
<dl>
<dd> Verification Code: <input type= "text" name= "code" class= "code"/></dd >
<dd><input type= "Submit" class= "Submit" value= "Validation"/></dd>
</dl>
</form>
</div>
</body>

3. Realization clicks the Verification Code picture Update Verification Code

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

Copy Code code as follows:

Window.onload = function () {
var code = document.getElementById (' codeimg ');//Find an IMG tag in HTML via ID
Code.onclick = function () {//Add click event for label
This.src= ' codeimg.php?tm= ' +math.random ()//modification time, pointing back to codeimg.php
};
}

Then you can <link> it 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.