[Code implementation] PHP generates various Random verification codes, and php generates verification codes.

Source: Internet
Author: User

[Code implementation] PHP generates various Random verification codes, and php generates verification codes.

Address: http://www.phpthinking.com/archives/531

Verification codes are very important in WEB applications. They are usually used to prevent users from submitting forms maliciously, such as malicious registration and login, and malicious Forum bumping. This article describes how to use PHP to generate various common verification codes, including the digit verification code, digit + letter verification code, Chinese verification code, arithmetic Verification Code, and its Ajax verification process.

Download sample source code PHP to generate Verification Code Image

How PHP generates a verification code: Use the GD library of PHP to generate an image with the verification code and save the verification code in the Session. The general process for generating a verification code in PHP is as follows:

1. Generate a png image;

2. Set the background color for the image;

3. Set the font color and style;

4. Generate a 4-digit random verification code;

5. Adjust the Rotation Angle and position of each character to png images;

6. Add noise and interference lines to prevent the registered machine from maliciously cracking the verification code by analyzing the original image;

7. output the image;

8. Release the memory occupied by images.

Sample Code.

Session_start (); getCode (4,60, 20); function getCode ($ num, $ w, $ h) {$ code = ""; for ($ I = 0; $ I <$ num; $ I ++) {$ code. = rand (0, 9);} // a four-digit verification code can also be directly generated using rand (,) // The generated verification code is written into the session, during backup verification, use $ _ SESSION ["helloweba_num"] = $ code; // create an image and define the color value header ("Content-type: image/PNG "); $ im = imagecreate ($ w, $ h); $ black = imagecolorallocate ($ im, 0, 0, 0); $ gray = imagecolorallocate ($ im, 200,200,200 ); $ bgcolor = imagecolorallocate ($ im, 255,255,255); // fill in the background imagefill ($ im, 0, 0, $ gray); // draw the border imagerectangle ($ im, 0, 0, $ W-1, $ h-1, $ black); // randomly draw two dotted lines to interfere with $ style = array ($ black, $ black, $ black, $ gray, $ gray); imagesetstyle ($ im, $ style); $ y1 = rand (0, $ h ); $ y2 = rand (0, $ h); $ y3 = rand (0, $ h); $ y4 = rand (0, $ h); imageline ($ im, 0, $ y1, $ w, $ y3, IMG_COLOR_STYLED); imageline ($ im, 0, $ y2, $ w, $ y4, IMG_COLOR_STYLED ); // randomly generate a large number of black spots on the canvas, which can interfere. for ($ I = 0; $ I <80; $ I ++) {imagesetpixel ($ im, rand (0, $ w), rand (0, $ h), $ black);} // randomly display numbers on the canvas, the horizontal spacing and position of characters are randomly generated according to a certain fluctuation range $ strx = rand (3, 8); for ($ I = 0; $ I <$ num; $ I ++) {$ strpos = rand (1, 6); imagestring ($ im, 5, $ strx, $ strpos, substr ($ code, $ I, 1 ), $ black); $ strx + = rand (8, 12);} imagepng ($ im); // output image imagedestroy ($ im); // release the memory occupied by the image}

In the code, the custom function getCode () interprets the verification code generation process. Using the image processing function provided by the php gd library, you can easily generate various desired image effects.

Imagecreate (): Creates a new image.

Imagecolorallocate (): assign color to the image

Imagefill (): Fill the image

Imagerectangle (): Draw a rectangle (Border)

Imagesetstyle (): sets the draw line style.

Imageline (): draw a line segment

Imagesetpixel (): pixel

Imagepng (): outputs an image to a browser or file in PNG format.

Imagedestroy (): releases the memory occupied by images.

Save the above Code as code_num.php for calling.

Ajax refresh and Verification

After the verification code is generated, we need to apply it in the actual project. Generally, we can use ajax to refresh the new verification code when clicking the verification code (sometimes the generated verification code is hard to recognize by the naked eye ), that is, "cannot see or change one ". After entering the verification code, you also need to verify that the entered verification code is correct. The verification process is completed by the background program, but we can also use ajax to implement no-refreshing verification.

We have created a front-end page index.html, loaded jquery, and added the verification code form element to the body:

<P> Verification Code: <input type = "text" class = "input" id = "code_num" name = "code_num" maxlength = "4"/>  </p> <input type =" button "class =" btn "id =" chk_num "value =" Submit "/> </p>

In the html code,

$ (Function () {// digit verification $ ("# getcode_num "). click (function () {$ (this ). attr ("src", 'Code _ num. php? '+ Math. random ());});...});

To refresh the verification code, you must re-request the Verification Code Generation Program. Note that random parameters must be included when you call code_num.php to prevent caching. After entering the verification code, click "Submit" and use $. post () to send an ajax request to the backend chk_code.php.

$ (Function (){... $ ("# chk_num "). click (function () {var code_num = $ ("# code_num "). val (); $. post ("chk_code.php? Act = num ", {code: code_num}, function (msg) {if (msg = 1) {alert (" the verification code is correct! ");} Else {alert (" Verification code error! ");}});});});

Backend chk_code.php Verification:

 session_start();  $code = trim($_POST['code']); if($code==$_SESSION["helloweba_num"]){    echo '1'; } 

The background compares the submitted verification code with the verification code saved in the session to complete the verification.

For the generation and use of other types of verification, the principle is the same. developers can generate multiple types of Random verification codes as needed, this demo provides a number verification code, a number + letter verification code, a Chinese verification code, a google-like verification code, and an arithmetic verification code.

Which of the following code writes a Random verification code using php?

Here is the PHP Verification Code class.

How can I obtain the value of the verification code from the following php code (output directly on the page)

Last two sentences:
$ Name = $ _ SESSION ['str'];
Echo $ name;
Remove it, because this php is actually represented as an image, and your echo won't have a value.
Last sentence $ _ SESSION ['str'] = $ str;
Save this file as checkimg. php
Create a PHP file under the same level directory.
A. php is as follows:
<? Php
Session_start ();

The verification code is:
Echo $ _ SESSION ["str"];

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.