"Code implementation" PHP generates various random verification codes

Source: Internet
Author: User

Article Source: PHP Development Learning Portal (self-developed personal website)

Verification codes are important in Web applications and are often used to prevent users from maliciously submitting forms, such as malicious registration and login, malicious forum flooding, and so on. This article will explain the use of PHP to generate a variety of common verification code including digital verification Code, Digital + letter verification Code, Chinese verification Code, arithmetic verification code, and its AJAX verification process.

Download Sample source code PHP Generate Verification Code picture

PHP generated Verification Code principle: the use of PHP's GD library, generate a picture with a verification code, and save the Verification code in the session. The approximate process for PHP to generate verification codes is:

1. Produce a picture of PNG;

2, set the background color for the picture;

3, set the font color and style;

4, generate 4-digit random verification code;

5. Adjust the rotation angle and position of each character produced to the PNG image;

6, add noise and interference lines to prevent the registration of machine analysis of the original image to maliciously crack verification code;

7, output pictures;

8. Release the memory of the image.

Sample code.

 session_start ();  getcode (4,60,20);   function getcode ($num, $w, $h)  {       $code  =  ";     for  ($i  = 0;  $i   <  $num;  $i + +)  {          $code  .= rand (0, 9); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//4-bit verification code can also be generated directly with Rand (1000,9999)       //writes the generated verification code to the SESSION and uses      $_session["Helloweba_num" for authentication]  =  $code;      //Create a picture, define a 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 Background       imagefill ($im, 0, 0,  $gray);       //frame       imagerectangle ($im, 0, 0,  $w -1,  $h -1,  $black);       //randomly draws two dashed lines, jamming       $style  = array  ($black, $black, $black, $black, $black,          $gray, $gray, $gray, $gray, $gray             imagesetstyle ($im,  $style);       $y 1 = rand (0,  $h);      $y 2 = rand (0,  $h);       $y 3 = rand (0,  $h);      $y 4 = rand (0,   $h)      imageline ($im, 0,  $y 1,  $w,  $y 3, img_color_ styled);    &nBsp; imageline ($im, 0,  $y 2,  $w,  $y 4, img_color_styled);       //randomly generates a large number of black dots on the canvas and acts as a distraction;     for  ($i  = 0;  $i  <  80;  $i + +)  {         imagesetpixel ($im,  rand ( 0,  $w),  rand (0,  $h),  $black);     }      Randomly displays numbers on the canvas, where the horizontal spacing and position of the characters are randomly generated by a range of fluctuations       $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 Picture      imagedestroy ($im);// Release the memory &nbsp of the image;}

In the code, the Custom Function GetCode () interprets the validation code generation process. Using the PHP GD Library's own image processing function, can easily generate a variety of desired image effects.

imagecreate (): Create a new image

imagecolorallocate (): assigning colors to images

Imagefill (): Fill image

Imagerectangle (): Draw a rectangle (border)

Imagesetstyle (): Set the line drawing style

imageline (): Draw a line segment

Imagesetpixel (): Draw dots of pixels

imagepng (): Output images to a browser or file in PNG format

Imagedestroy (): Release the memory of the image

Save the above code as code_num.php so that it can be called.

Ajax Refresh and Validation

After the verification code is generated, we are going to apply it in the actual project, usually we can use AJAX to achieve the Click Verification Code refresh generate a new verification code (sometimes generated verification code is difficult to recognize the naked eye), that is, "can't see a change." After completing the verification code, you also need to verify that the verification code is correct, the process of verification is to the background program to complete, but we can also use Ajax to achieve no refresh verification.

We set up a front-end page index.html, load jquery, and add a captcha form element to the body:

<p> captcha: <input type= "text" class= "input" id= "Code_num" name= "Code_num" maxlength= "4"/> </p> <p><input type=" button "class=" BTN "id=" Chk_num "value=" Commit "/></p>

In the HTML code,

$ (function () {//Numeric authentication $ ("#getcode_num"). Click (function () {$ (this). attr ("src", ' code_num.php? ' + math.random (     ));     }); ... });

refresh the verification code, in fact, is to re-request the Verification code generation program, It is important to note that when calling code_num.php, a random parameter is taken to prevent caching. Next fill in the Verification code, click the "Submit" button, through $.post (), the front-end back to the chk_code.php to send AJAX requests.

  $ (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 ("Captcha Error! ");             }          });      });  }); 

Background chk_code.php Verification:

Session_Start (); $code = Trim ($_post[' code '); if ($code ==$_session["Helloweba_num"]) {echo ' 1 ';}

The background is verified by the verification code that is submitted and saved in the session.

For the other several kinds of verification of the generation and use, the same principle, the developer can produce a variety of styles of random verification Code, the demo provides a digital verification code, Digital + letter verification Code, Chinese verification Code, imitation Google Verification Code, arithmetic verification code and so on.


"Code implementation" PHP generates various random verification codes

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.