PHP implementation dynamic random verification code mechanism

Source: Internet
Author: User
Tags format bool final header pack php code string strlen
  Verification Code (CAPTCHA) is an abbreviation for "completely automated public Turing test to tell Computers and humans Apart" (fully automatic distinguishing between computer and human Turing tests) A public fully automated procedure for distinguishing whether a user is a computer or a 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 introduction to the image processing of PHP.   A. 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.         General generated graphics, stored through the document format of PHP, 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. Sets 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 graphical outline on the background to enter text.   5). Output final graphics.   6). Clear all resources.   7). Other pages call the image.   The first step, set the file MIME type, output type to change the output type to the image stream header (' content-type:image/png; ');   generally generated images can be png,jpeg,gif,wbmp   Step two, create a graphics area, figureLike a background imagecreatetruecolor () returns an image identifier that represents a black image of x_size and y_size size. Syntax: Resource imagecreatetruecolor (int $width, int $height)   $im = Imagecreatetruecolor (200,200);   In the third step, draw the fill background   the color filler in the blank image area; imagecolorallocate--Assign 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--Region fill; Syntax: bool Imagefill (Resource $image, int $x, int $y, int $color)   Imag Efill ($im, 0,0, $blue);   Fourth step, on the blue background to enter some lines, text, such as color filler   $white = imagecolorallocate ($im, 255,255,255);   Draw two line segments: Imageline   Imageline () draws a line segment from the coordinates 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)   Imageline ($im, 0,0,200,20 0, $white);   Imageline ($im, 200,0,0,200, $white);   horizontally draw a string of strings: Imagestring   imagestring () draws the string s to the x,y coordinates of the image represented by images in Col color (this is the upper-left corner of the string, and 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,2 0, ' Jingwhale ', $white);   Fifth, the output final graphics imagepng () outputs the GD image Stream (image) in PNG format to standard output (typically a browser), or outputs it to the file if the filename is given by filename. Syntax: BOOL Imagepng (Resource $image [, String $filename])   imagepng ($im);   Sixth, I'm going to empty all the resources Imagedestroy () to free the memory associated with the image. Syntax: BOOL Imagedestroy (Resource $image)   Imagedestroy ($im);   other page (HTML) calls create graphics   Sample code as follows:   Copy code <?php    // The first step is to set the file MIME type     header (' content-type:image/png; ');         //Step two, 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 on the blue background, text etc   &NBsp $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 clear all the resources of the     Imagedestroy ($im);    ?> Copy code display effect:   image       two. To create a dynamic authentication code: Code Source Address Https://github.com/cnblogs-/php-captcha   1. Create a picture with verification code, and fuzzy background random code using 16; Fuzzy background is the picture background with lines, snowflakes and so on.   1 Create random code      for ($i =0 $i <$_rnd_code; $i + +) {        $_nmsg. = Dechex (Mt_rand (0,15));    } string dechex (int $number), returns a string containing the hexadecimal representation of the given number parameter.   2 Save in session     $_session[' Code ' = $_nms 3) Create picture   Copy code//Create an image $_img = Imagecreatetruecolor ($_wid Th,$_height);  //White $_white = Imagecolorallocate ($_img,255,255,255);  //Filling Imagefill ($_img,0,0,$_white); &nbsP if ($_flag) {//Black, border     $_black = Imagecolorallocate ($_img,0,0,0);     Imagerectangle ($_img,0,0,$_w Idth-1,$_height-1,$_black); Copy code 4) Blur background   Copy code//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);   &NBSP  //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);   &NBSP (copy code 5) output and destroy   copy code for ($i =0; $i <strlen ($_session[' code '); $i + +) {      &NB Sp $_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); The copy code encapsulates it 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 Verification Code length: If you want 6-bit length recommended 75+50, if you want 8-bit, recommended 75+50+50, and so on * @param int $_height Verification Code Height * @param int $_rnd_co Number of digits of de verification code * @param bool $_flag Verify code needs a border: True has borders, false borderless (default)   encapsulated code as follows:   Copy code <?php /**  * &NB Sp    [verification-code] (C) 2015-2100 Jingwhale.  *        *      this is a freeware  *       $ID: GLOBAL.FUNC.P HP 2015-02-05 20:53:56 jingwhale$  *//**  * () is a validation code function _code @access public  * @param int  * authentication Code Length: If you want to 6-bit length recommended 75+50; If you want 8 bits, recommend 75+50+50, and so on  * @param int $_height The height of the authentication code  * @param int $_rnd_code authentication code number of digits  * @ param bool $_flag Verify code requires a border: True has a border, false no border (default)  * @returnVoid this function executes to produce a captcha  */function _code ($_width = 75,$_height = 25,$_rnd_code = 4,$_flag = False) {    &nbs P Create a random code     for ($i =0 $i <$_rnd_code; $i + +) {        $_nmsg. = Dechex (Mt_rand (0,15)); &nbs P  }      //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 = Imagecolorall Ocate ($_img,0,0,0);         Imagerectangle ($_img,0,0,$_width-1,$_height-1,$_black);    }      //immediately 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_CO Lor = 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);      /destroy     IMAGEDESTROy ($_IMG); ?> Copy Code 2. Create a validation mechanism to create a PHP validation page that verifies that the code is consistent by session.   1 Create verification-code.php validation page   copy code <?php /**  *      [verification-code] (C) 2015-2100 Jingwhale.  *  *      this is a freeware  *       $Id: verification-code.php 2015-02-05 2 0:53:56 jingwhale$  */ //Set Character Set encoding header (' content-type:text/html; Charset=utf-8 ');?>   <! DOCTYPE html>

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.