PHP implementation to generate background-coded graphics verification code function _php skills

Source: Internet
Author: User
Tags rand strlen

This article describes the PHP implementation of the generation with background graphics verification code function. Share to everyone for your reference, specific as follows:

We used to generate all of PHP is no background or the same color background of the verification code, but this validation is easy to identify the machine, here to introduce some generation with background graphics verification code examples.

1, to produce a picture of PNG,
2, set the background color for the picture,
3, set the font color and style,
4, generate a 4-digit random verification code,
5, the resulting each character adjusted rotation angle and position to the PNG picture,
6, add noise and interference line to prevent the registration machine analysis of the original picture to malicious registration,
7, Output pictures,
8, free up the image of memory

authcode.php file, the code is as follows:

<?php session_start ();
    Header (' content-type:image/png ');
    Create a 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 background color of the palette-based image $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, where you can replace other font styles//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;//user and user input authentication codes for 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 session session_start ();
Define foreground display verification code length & width $image _width = 120;
$image _height = 40;
$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 = 10;
$random _lines = 30;
$captcha _text_color= "0x142864";
$captcha _noice_color = "0x142864";
Defines the string $code = ' "To generate the verification 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 noise 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_ran
D (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_ran D (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 _width-$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 is shown I N Browser widow imagejpeg ($image);//showing the image ImageDestroy ($image);//destroying the image instance//set session, do validation $_session[' 6_letters_code '] = $code;
 function Hexrgb ($hexstr) {$int = Hexdec ($HEXSTR); Return Array ("Red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "b
Lue "=> 0xFF & $int);

 }

The

Displays the authentication code page index.php, with the instance code as follows:

<?php session_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 have entered the wrong authentication code, please re-enter!";}
    else{echo "You typed it right!"; Captcha verification is correct.
  Final Code Execute here!
  }?> <style type= "Text/css" > table{, Font-family:arial, Helvetica;
  font-size:12px;
  Color: #333;
Background-color: #E4E4E4; }. Table td{Background-color: #F8F8F8;} </style> <form action= "" method= "Post" Name= "Form1" Id= "Form1" > & Lt;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" > Authentication code demo:</td> <td> "id= ' captchaimg ' onclick=" Refreshcaptcha (); "><br> <label for= ' message ' > Please enter the verification code:</label> <br> <input id= "6_letters_code" name= "6_letters_code" type= "text" > <br> if you don't see it, please <a href= ' Javascript:refreshcaptcha (); '
    > Point I </a> Refresh! </p></td> </tr> <tr> <td>&nbsp;</td> <td><input name= "Submit" t Ype= "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 following:

<?session_start ();? > <form method=post action= "" > <input type=text name=number maxlength=4> <input type=" Submit "Name=" sub "> </FORM> Verify 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 "Check code is incorrect!";} else{echo "Verification code passed!
";
}
endif
Show_source (' test.php ');
The above source code//Below is the source code show_source (' yanzhengma.php ') to generate the verification code;?> <?php session_start ();
Session_register ("Login_check_number");  Last night saw the verification code effect on the Chianren, consider a bit, using PHP's GD library to complete a similar function//first genetic background, and then the generated verification of the stacking up $img _height=120;
First define the long, wide $img _width=40 of the picture; if ($HTTP _get_vars["act"]== "init") {//srand (Microtime () * 100000);//php420 is not a required for ($Tmpa srand; $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")); Generates a 4-bit random number and puts it into SessiOn//Who can make the supplement, can generate letters and numbers at the same time??  The----was completed by sports98 $aimg = Imagecreate ($img _height, $img _width);      Generate Picture Imagecolorallocate ($aimg, 255,255,255);    Picture background, imagecolorallocate the 1th time the definition of color 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);//First into a black rectangle to surround the picture///below to create a snowflake background, In fact, it is in the picture generated some symbols for ($i =1 $i <=100; $i + +) {//First Test with 100 imagestring ($aimg, 1,mt_rand (1, $img _height), Mt_rand (1, $img
    _width), "*", Imagecolorallocate ($aimg, Mt_rand (200,255), Mt_rand (200,255), Mt_rand (200,255)); Ha, see it, in fact, is not a snowflake, is to generate the * number just.
  In order for them to look "cluttered, 5-color, 6", they have to have their position, color, or even size randomly counted at 1 1, and rand () or mt_rand can do it. ///The background is generated, now it's time to put the generated random numbers up. The reason is similar to the above, random number 1 1 places, at the same time let their position, size, color used into random number ~ ~//In order to distinguish from the background, the color here is not more than 200, the above is not less than 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, the following data is a picture, rather than the text display imagepng ($AIMG); Generate PNG format ...
  The effect is quite like a matter of ...
Imagedestroy ($AIMG);

 }?>

For more information on PHP related content readers can view the site topics: "PHP graphics and pictures Operating skills summary", "Basic PHP Grammar Introductory Course", "PHP Operations and Operator Usage Summary", "PHP object-oriented Program Design Introductory Course", "PHP Network Programming Skills Summary", "PHP array (Array) Operations tips Encyclopedia, "PHP string (String) Usage Summary", "Php+mysql Database operation Introduction Tutorial" and "PHP Common database Operation tips Summary"

I hope this article will help you with the PHP program design.

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.