PHP implementation of dynamic random verification Code mechanism (CAPTCHA)

Source: Internet
Author: User
Tags image identifier

Implementation of dynamic random verification code mechanism in PHP

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 that represents a x_size black image with a size y_size of. 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 = Imagecolorallocate ($im, 0,102,255);

Fill the blue color to the background; Imagefill-area fill; Syntax: bool Imagefill (Resource $image , int, int $x $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 () color draws a line segment with color in the image image from coordinates x1 , y1 to x2 , y2 (0, 0 in the upper-left corner of the image). Syntax: BOOL Imageline (Resource $image , int, int, $x1 int, $y1 $x2 int $y2 , 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 col color to draw the string to the coordinates of the s image represented image x (this is the upper-left coordinate of the string, and the upper- y left corner of the image is 0,0). If font it 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 filename outputs it to the file if it is given a file name. Syntax: BOOL Imagepng (Resource $image [, String $filename ])

Imagepng ($im);

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

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

Imagedestroy ($im);

Other pages (HTML) call the created graphic

The sample code is 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 graphicsImagepng ($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

 for ($i= 0; $i<$_rnd_code; $i++)        {$_nmsgdechex(mt_rand(0,15));    }

String Dechex (int $number ) that returns a string that contains number the hexadecimal representation of the given parameter.

2) Save in session

$_session $_nms

3) Create a picture

// 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);}

4) Blur background

//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); }//RandomSnowflakes 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); // Destruction of 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:

 
  /* * *      [Verification-code] (C) 2015-2100 Jingwhale. *       * This is      a freeware *      */
/** * _code () is the CAPTCHA function * @access public * @param int $_width Verification Code length: If you want 6-bit length recommended 75+50, if you want 8 bit, recommend 75+50+50, and so on * @param int $_he ight 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 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.=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); //FillImagefill ($_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<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); //destroyedImagedestroy ($_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

 
  /* * *      [Verification-code] (C) 2015-2100 Jingwhale. * * This is      a freeware *      * */ / Set the CharSet encoding header(' content-type:text/ html Charset=utf-8 ');? >    
 
      Verification Code    
 
                  

Shown below:

2) Create a Verification code page

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

 
  /* * *      [Verification-code] (C) 2015-2100 Jingwhale. *       * This is      a freeware *      * */ / open sessionsession_start( ); // introducing the 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

The session must first be opened 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 201 5-02-05 20:53:56 jingwhale$*///setting Character Set encodingHeader(' content-type:text/html; Charset=utf-8 ');//Open SessionSession_Start();//introducing the Global function library (custom)require dirname(__file__).' /includes/global.func.php ';//Inspection Verification Codeif($_get[' action '] = = ' Verification ') {        if(! ($_post[' code '] = =$_session[' Code ']) {_alert_back (' The verification code is not correct! '); }Else{_alert_back (' Verification code passed! '); }}  ?>    
 
  
     <title>Verification Code</title>    
 
  
                     

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

function () {    var code = document.getElementById (' codeimg ');   by ID find the img tag    function () {/// to add a click event for the tag in HTML        . 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 .

Finish

Welcome reprint. Reprint please specify the reproduced words, mark the original author and the original post address.

The above describes the PHP implementation of dynamic random verification Code mechanism (CAPTCHA), including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

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