Summary of methods for generating various random verification codes in PHP

Source: Internet
Author: User
This article mainly introduces PHP generate a variety of random verification code method, combined with specific examples of the form of PHP commonly used to generate verification code operation related skills, and with the demo source for the reader to download the reference, the need for friends can refer to the next

This paper summarizes the methods of generating various random verification codes in PHP. Share to everyone for your reference, as follows:

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.

Click here to download the 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.

Example code:


Session_Start (); GetCode (4,60,20); function GetCode ($num, $w, $h) {$code = "";  for ($i = 0; $i < $num; $i + +) {$code. = rand (0, 9);  }//4-bit verification code can also be generated directly with Rand (1000,9999)//The generated verification code is written to the SESSION, the verification with $_session["helloweba_num"] = $code;  Create a picture, 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 Background imagefill ($im, 0, 0, $gray);  Draw Border Imagerectangle ($im, 0, 0, $w-1, $h-1, $black);  Randomly draws two dashed lines, acts as a disturbance $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);  Imageline ($im, 0, $y 2, $w, $y 4, img_color_styled);  A large number of black dots are randomly generated on the canvas, which acts as interference;  for ($i = 0; $i <; $i + +) {Imagesetpixel ($im, rand (0, $w), rand (0, $h), $black); }//numbers are randomly displayed in theOn the canvas, 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 Image Memory}


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(): Releases 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 () {  //digital 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 generator, it is important to note that when calling code_num.php with random parameters 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 ("Captcha 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.

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.