On the method of making dynamic random verification code in PHP

Source: Internet
Author: User
Tags image identifier
This article mainly introduces the PHP production of dynamic random verification Code of the relevant information, the need for friends can refer to the following

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

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)

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

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

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

Fourth step, 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 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)

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)

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

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)

Imagedestroy ($im);

Other pages (HTML) call the created graphic

The sample code is as follows:

<?php    //First step, set file MIME type    header (' content-type:image/png; ');    The second step, create a graphics area, image background    $im = Imagecreatetruecolor (200,200);    The third step is to 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 on the blue background, text, etc.    $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 want to empty all the resources    Imagedestroy ($IM);    >

Display effect:

Two. Create a dynamic verification code

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

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

$_session[' Code ' = $_nms

3) Create a picture

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

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

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);//Destroy 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:

<?php/** * [Verification-code] (C) 2015-2100 Jingwhale. * * This is a freeware * $Id: global.func.php 2015-02-05 20:53:56 jingwhale$ *//** * _code () is the CAPTCHA function * @acce SS Public * @param int $_width The length of the verification code: if you want 6-bit length recommended 75+50, if you want 8-bit, recommend 75+50+50, and so on * @param int $_height Verification Code Height * @param int $_rnd  _code 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 This function produces a verification code */function _code ($_width = 75,$_height = 25,$_rnd_code = 4,$_flag = False) {//Create random code for ($i =0; $i <$_rnd_code; $i + +) {$_nmsg. = Deche    X (Mt_rand (0,15));    }//saved in SESSION $_session[' code ' = $_nmsg;    Create an image $_img = Imagecreatetruecolor ($_width,$_height);    White $_white = imagecolorallocate ($_img,255,255,255);    Filling 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 snowflake 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,        , 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); Destroy 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

<?php/** *      [Verification-code] (C) 2015-2100 jingwhale. * * This is      a freeware *      $Id: verification-code.ph P 2015-02-05 20:53:56 jingwhale$ *///set Character Set encoding header (' content-type:text/html; Charset=utf-8 ');? ><! DOCTYPE html>

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 ();

<?php/** *      [Verification-code] (C) 2015-2100 jingwhale. *       * This is      a freeware *      $Id: codeimg.php 2015 -02-05 20:53:56 jingwhale$ *///Open Sessionsession_start ();//introduce global function library (custom) require dirname (__file__). ' /includes/global.func.php ';//Run the CAPTCHA function. Through the database _code method, set the various properties of the verification code, generate 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:

<?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-ty pe:text/html; Charset=utf-8 ');//Open Sessionsession_start ();//introduce global function library (custom) require dirname (__file__). ' /includes/global.func.php ';//Verification code if ($_get[' action '] = = ' Verification ') {if (! (    $_post[' code ' = = $_session[' Code ']) {_alert_back (' incorrect captcha! '); }else{_alert_back (' Verification code passed!    '); }}? ><!    DOCTYPE html>

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

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

Then in the verification-code.php HTML code head <link> it can.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Related Article

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.