Php implements the Dynamic random verification code mechanism (CAPTCHA). captcha_PHP tutorial

Source: Internet
Author: User
Php implements CAPTCHA and captcha. Php implements the Dynamic random verification code mechanism (CAPTCHA), captchaphp implements the Dynamic random verification code mechanism (CAPTCHA) is "CompletelyAutomatedPublicTuringtesttotel php implements the Dynamic random verification code mechanism (CAPTCHA), captcha
Dynamic random verification code in php

CAPTCHA is short for "Completely automatic Public Turing test to tell Computers and Humans Apart" (a Completely Automated Turing test that distinguishes Computers from Humans, it is a fully-automated public program that distinguishes a user from a computer or a person. It can prevent malicious password cracking, ticket flushing, and forum bumping, effectively preventing a hacker from continuously logging on to a specific registered user using brute force cracking methods of specific programs, in fact, the verification code is now used by many websites. we have implemented this function in a relatively simple way.

This question can be generated and judged by computers, but it must be answered by humans. Because the computer cannot answer CAPTCHA's questions, users who answer questions can be considered as humans.

Php makes a dynamic verification code based on php image processing. The following describes the php image processing.

I. INTRODUCTION to php image processing

In PHP5, processing of dynamic images is much easier than before. PHP5 contains the GD extension package in the php. ini file. you only need to remove the corresponding comments of the GD extension package to use it normally. The GD Library in PHP5 is the upgraded GD2 Library, which contains some useful JPG functions that support true color image processing.

Generally, generated images are stored in the PHP document format, but dynamic images can be directly obtained through the HTML image insertion method SRC. For example, verification code, watermark, and thumbnail.

General process for creating images:

 

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

2) create an image region based on which operations will be performed in the future.

3) fill the background in the blank image area.

4) draw the input text of the graphic outline on the background.

5). output the final image.

6) clear all resources.

7). call images on other pages.

Step 1: Set the file MIME type, and change the output type to image stream.
 

header('Content-Type: image/png;');

Generally, the generated image can be png, jpeg, gif, or wbmp.

Step 2: create a graphic area and image background

Imagecreatetruecolor ()Returns an image identifier, representing the size of an image.x_sizeAndy_sizeBlack image. Syntax: resourceImagecreatetruecolor(Int$width, Int$height)

 

$im = imagecreatetruecolor(200,200);

Step 3: draw a filling background in the blank image area

Color filler; imagecolorallocate -- assign color to an image; syntax: intImagecolorallocate(Resource$image, Int$red, Int$green, Int$blue)

 

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

Fill the blue color to the background; imagefill -- fill the area; syntax: boolImagefill(Resource$image, Int$x, Int$y, Int$color)

 

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

Step 4: enter some lines and text on the blue background

Color filler

 

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

Draw two line segments: imageline

Imageline ()UsecolorColor in imageimageFrom coordinatesx1,y1Tox2,y2(0 in the upper left corner of the image) draw a line segment. Syntax: boolImageline(Resource$image, Int$x1, Int$y1, Int$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 ()UsecolColor stringsImageimageThex,yCoordinates (this is the coordinate of the upper left corner of the string, and the upper left corner of the entire image is 0, 0 ). IffontIf it is 1, 2, 3, 4, or 5, the built-in font is used. Syntax: boolImagestring(Resource$image, Int$font, Int$x, Int$y, String$s, Int$col)

 

imagestring($im,5,66,20,'jingwhale',$white);

Step 5: output the final image

Imagepng ()Convert the GD image stream (image) Output to the standard output in PNG format (usually in a browser), orfilenameIf the file name is given, it is output to the file. Syntax: boolImagepng(Resource$image[, String$filename])

 

imagepng($im);

Step 6: I want to clear all the resources

Imagedestroy ()Release andimageMemory. Syntax: boolImagedestroy(Resource$image)

 

imagedestroy($im);

Images created by calling other pages (html)
 

The sample code is as follows:

 

Display effect:

2. create a dynamic verification code

Appendix: code source address https://github.com/cnblogs-/php-captcha

1. create an image with a verification code and blur the background.

The random code is in hexadecimal notation. blur the background to add lines and snow to the image background.

1) create a random code

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

StringDechex(Int$number), Returns a string containing the givennumberThe hexadecimal representation of the parameter.

2) save in session

$_SESSION['code'] = $_nms

3) create an image

// Create an image $ _ img = imagecreatetruecolor ($ _ width, $ _ height); // white $ _ white = imagecolorallocate ($ _ img, 255,255,255 ); // fill in imagefill ($ _ img, $ _ white); if ($ _ flag) {// black, border $ _ black = imagecolorallocate ($ _ img, 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 the verification code for ($ I = 0; $ I
 
  

Encapsulate it in the global. func. php global function library. the function name is _ code () for calling. We will set four parameters $ _ width, $ _ height, $ _ rnd_code, and $ _ flag to improve the flexibility of functions.

* @ ParamInt $ _ widthLength of the verification code: recommended for 6-digit length: 75 + 50; recommended for 8-digit length: 75 + 50 + 50, and so on
* @ ParamInt $ _ heightHeight of the verification code
* @ ParamInt $ _ rnd_codeNumber of digits of the verification code
* @ ParamBool $ _ flagBorder required for verification code: true with border, false without border (default)

The encapsulated code is as follows:

   
/*** _ Code () is the length of the verification code function * @ access public * @ param int $ _ width: 75 + 50 is recommended for 6 characters; if you want 8 digits, we recommend 75 + 50 + 50, and so on * @ param int $ _ height verification code height * @ 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 generates 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 ();} // save it in session $ _ SESSION ['code'] =$ _ nmsg; // create an image $ _ img = imagecreatetruecolor ($ _ width, $ _ height); // white $ _ white = imagecolorallocate ($ _ img, 255,255,255 ); // fill in imagefill ($ _ img, $ _ white); if ($ _ flag) {// black, border $ _ black = imagecolorallocate ($ _ img, 0); imagerectangle ($ _ img, 0, 0, $ _ width-1, $ _ height-1, $ _ black );} // 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);} // Snow 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 the verification code for ($ I = 0; $ I
    
2. create a verification mechanism

Create a php verification page and use session to check whether the verification code is consistent.

1) create verification-code.php verification page

        
        Verification code    
        

Shown as follows:

2) create a verification code Image page

Create codeimg. php to provide verification code Image for img in verification-code.php html code

First, you must enable the session on the codeimg. php page;

Secondly, we will introduce the encapsulated global. func. php global function Library;

Finally, run _ code ();

    

3) Create a session check mechanism

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

Secondly, the verification code is designed to be submitted. this document submits the verification code in get mode. when action = verification, the verification code is submitted successfully;

Finally, create a verification function to verify the verification code submitted by the client user with the server codeimg. check whether the session verification code in php is consistent. here is a js pop-up function _ alert_back (), which is also encapsulated in global. func. in php;

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

        
        Verification code    
        

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.