PHP implementation to generate a graphical verification code with the background function

Source: Internet
Author: User
In this paper, the implementation of PHP to generate a background of the graphics verification code function. Share to everyone for your reference, as follows:

In the past, we used PHP to generate no background or the same color background verification code, but this kind of verification is easy for the machine to recognize, here is to introduce some of the generation of the background of the graphic verification code examples.

1. Produce a picture of PNG,
2, set the background color for the picture,
3. Set the font color and style,
4, the generation of 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 line to prevent the registration machine analysis of the original image to malicious registration,
7, Output pictures,
8. Release the memory of the image

authcode.php file with the following code:

<?php session_start ();    Header (' content-type:image/png ');    Create Picture $im = Imagecreate ($x =130, $y = 45); $BG = Imagecolorallocate ($im, Rand (50,200), Rand (0,155), Rand (0,155));  The first call to Imagecolorallocate () fills the color palette-based image with the background color $fontColor = imagecolorallocate ($im, 255, 255, 255);          Font Color $fontstyle = ' Rock.ttf ';        Font style, this can be found from the C:windowsfonts folder, I put it in the same directory as the authcode.php file, here can replace the other font style//generate random characters for ($i = 0; $i < 4; $i + +) {        $randAsciiNumArray = Array (rand (48,57), Rand (65,90));        $randAsciiNum = $randAsciiNumArray [Rand (0, 1)];        $RANDSTR = Chr ($randAsciiNum);        Imagettftext ($im, 30,rand (0,20)-rand (0,25), 5+ $i *30,rand (30,35), $fontColor, $fontstyle, $RANDSTR);    $authcode. = $RANDSTR; } $_session[' Authcode ' = $randFourStr;//The user and user entered the verification code to do the comparison//interference line for ($i =0; $i <8; $i + +) {$lineColor =        Imagecolorallocate ($im, Rand (0,255), Rand (0,255), Rand (0,255)); Imageline ($im, Rand(0, $x), 0,rand (0, $x), $y, $lineColor);    }//Interference point for ($i =0; $i <250; $i + +) {Imagesetpixel ($im, rand (0, $x), rand (0, $y), $fontColor);    } imagepng ($im); Imagedestroy ($im);? >

Example 2, create a new PHP file captcha_code_file.php, with the following code:

First open Sessionsession_start ();//define the foreground display verification code length & Width $image_width = +; $image _height = +; $characters _on_image = 6; $font = './monofont.ttf ';//the characters that can is used in the CAPTCHA code.//avoid confusing characters (l 1 and I for example ) $possible _letters = ' 23456789bcdfghjkmnpqrstvwxyz '; $random _dots = ten; $random _lines = $captcha _text_color= " 0x142864 "; $captcha _noice_color =" 0x142864 ";//define the string to generate the verification code $code = '; $i = 0;while ($i < $characters _on_image) {$code. = substr ($possible _letters, Mt_rand (0, strlen ($possible _letters)-1), 1); $i + +;} $font _size = $image _height * 0.75; $image = @imagecreate ($image _width, $image _height);/* Setting the background, text and n Oise colours here */$background _color = imagecolorallocate ($image, 255, 255, 255); $arr _text_color = Hexrgb ($captcha _text _color); $text _color = Imagecolorallocate ($image, $arr _text_color[' Red '], $arr _text_color[' green ', $arr _text_color[ "Blue"); $arr _noice_color = Hexrgb ($captcha _noice_color); $image _noise_color = ImagecolorallOcate ($image, $arr _noice_color[' red '), $arr _noice_color[' green '], $arr _noice_color[' Blue ');/* Generating the dots Randomly in background */for ($i =0; $i < $random _dots; $i + +) {imagefilledellipse ($image, Mt_rand (0, $image _width), Mt_ Rand (0, $image _height), 2, 3, $image _noise_color);} /* generating lines randomly in background of image */for ($i =0; $i < $random _lines; $i + +) {imageline ($image, Mt_rand (0, $image _width), Mt_rand (0, $image _height), Mt_rand (0, $image _width), Mt_rand (0, $image _height), $image _noise_color);} /* Create a text box and add 6 letters code in IT */$textbox = Imagettfbbox ($font _size, 0, $font, $code); $x = ($image _widt H-$textbox [4])/2; $y = ($image _height-$textbox [5])/2;imagettftext ($image, $font _size, 0, $x, $y, $text _color, $font, $ code);/* Show captcha image in the page HTML page */header (' content-type:image/jpeg ');//Defining the image Type to be sh Own in Browser widowimagejpeg ($image);//showing the Imageimagedestroy ($image);//destroying the image instance//setSet SESSION, do verify $_session[' 6_letters_code '] = $code, function Hexrgb ($hexstr) {$int = Hexdec ($HEXSTR); return Array ("Red" =& Gt 0xFF & ($int >> 0x10), "green" + 0xFF & ($int >> 0x8), "Blue" + 0xFF & $int) ;}

The

Displays the Captcha page index.php, with the following instance code:

<?phpsession_start (); if (Isset ($_request[' Submit ')) {//code for check server side validation if (Emptyempty ($_    session[' 6_letters_code ') | | STRCASECMP ($_session[' 6_letters_code '), $_post[' 6_letters_code '])! = 0) {$msg = "You entered the wrong code, please re-enter!"}    else{echo "You have entered the correct!"; Captcha verification is Correct.  Final Code Execute here!  }}?><style type= "Text/css" >.table{font-family:arial, Helvetica, Sans-serif;  font-size:12px;  Color: #333; Background-color: #E4E4E4;}. Table td{Background-color: #F8F8F8;} </style><form action= "" method= "Post" Name= "Form1" Id= "Form1" > <table width= "" "border=" 0 "align=" Center "cellpadding=" 5 "cellspacing=" 1 "><?php if (Isset ($msg)) {?> <tr> <td colspan=" 2 "align=" Center "Valign=" Top "><?php echo $msg;? ></td> </tr><?php}?> <tr> <td align= "right" valign= "top" > Verification Code demo:</td> &lt ; td><br> <label for= ' message ' > Please enter the captcha:</label> <b r> <input id= "6_letters_code" name= "6_letters_code" type= "text" > <br> if not visible, please <a href= ' JAVASCRI Pt:refreshcaptcha (); '    > Point me </a> Refresh! </p></td> </tr> <tr> <td>&nbsp;</td> <td><input name= "Submit" type= "Submit" onclick= "return Validate ()" value= "Submit" ></td> </tr> </table></form><  Script type= ' text/javascript ' >//defined refresh request function Refreshcaptcha () {var img = document.images[' captchaimg ']; IMG.SRC = img.src.substring (0,img.src.lastindexof ("?")) + "? rand=" +math.random () *1000;} </script>

Example 3, with a snowflake background verification code, the code is as follows:

<?session_start ();? ><form method=post action= "" ><input type=text name=number maxlength=4><input type=" Submit "Name=" Sub "></form><?//Check check code if (Isset ($HTTP _post_vars[" Sub "]): if ($ http_post_vars["Number"]! = $HTTP _session_vars[login_check_number] | | Emptyempty ($HTTP _post_vars["number"]) {echo "Checksum code is incorrect!"} else{echo "Verification code passed! ";} Endif;show_source (' test.php ');//The source code of the above page//below is the source code show_source (' yanzhengma.php ') to generate the verification code; ><?phpsession_start (); Session_register ("Login_check_number");//I saw the verification code effect on Chianren last night, and took a look at it.  Using the PHP GD library to complete a similar function//genetic background, and then the generated verification on the $img_height=120; Define the image's length, Width $img_width=40;if ($HTTP _get_vars["act"]== "init") {//srand (Microtime () * 100000)//php420, Srand is not required for ($Tmpa =0; $Tmpa <4; $Tmpa + +)  {$nmsg. =dechex (rand (0,15));  }//by sports98 $HTTP _session_vars[login_check_number] = $nmsg;  $HTTP _session_vars[login_check_number] = Strval (Mt_rand ("1111", "9999")); Generate 4-bit random numbers, put in the session//Who can do the next supplement, you can generate both letters and numbers AH?? ----bySports98 Completed $aimg = imagecreate ($img _height, $img _width);      Generate Picture Imagecolorallocate ($aimg, 255,255,255);    Image background, imagecolorallocate the 1th time to define the color of PHP is considered to be the background $black = Imagecolorallocate ($aimg, 0,0,0); Define the required black Imagerectangle ($aimg, 0,0, $img _height-1, $img _width-1, $black);//A black rectangle to enclose the picture//the next one to create a snowflake background, In fact, it is to generate some symbols for ($i =1; $i <=100; $i + +) {/////test with 100 first imagestring ($aimg, 1,mt_rand (1, $img _height), Mt_rand (1, $img _w    Idth), "*", Imagecolorallocate ($aimg, Mt_rand (200,255), Mt_rand (200,255), Mt_rand (200,255))); Ha, see, in fact, is not a snowflake, is to generate * number just.  To make them look "disorganized, 5 6", you have to generate them in 1 1, with random numbers for their position, color, and even size, which rand () or Mt_rand can do. }//above generates a background, it is time to put the generated random number up. The truth and the above, random number 1 1 places, at the same time let their position, size, color are used random number ~//In order to distinguish from the background, the color here is not more than 200, the above is not less than a for ($i =0; $i <strlen ($HTTP _session_ Vars[login_check_number]) ($i + +) {imagestring ($aimg, Mt_rand (3,5), $i * $img _height/4+mt_rand (1,10), Mt_rand (1, $img _ WIDTH/2), $HTTP _session_vars[login_check_number][$i],imagecolorallocate ($aimg, Mt_rand (0,100), Mt_rand (0,150), Mt_ Rand (0,200)));  } Header ("Content-type:image/png");          Tell the browser that the following data is a picture, and do not display Imagepng ($aimg) as text; Generate PNG format ...  Hey, the effect is pretty much like a thing ... Imagedestroy ($aimg);}? >

I hope this article is helpful to you in PHP programming.

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.