PHP generates a graphic verification code program with background

Source: Internet
Author: User

In the past, we used php to generate verification codes without background or with the same color background. However, this verification is easy for the machine to recognize. I will introduce some examples of generating graphic verification codes with background.

Example

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 generated character to the png image.
6. Add noise and interference lines to prevent registration machines from malicious registration by analyzing original images
7. output image
8. release memory occupied by images
Authcode. php file

Code

The Code is as follows: Copy code
<? Php
Session_start ();
Header ('content-type: image/png ');
// Create an image
$ Im = imagecreate ($ x = 130, $ y = 45 );
$ Bg = imagecolorallocate ($ im, rand (50,200), rand (0,155), rand (0,155); // The First Time on imagecolorallocate () will fill the background color for the image based on the color palette.
$ FontColor = imageColorAllocate ($ im, 255,255,255); // font color
$ Fontstyle = 'Rock. ttf'; // font style, which can be found in the c: windowsFonts folder. I put it in the same way as authcode. the PHP file is in the same directory. Other font styles can be replaced here.
// 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 ()-rand (), 5 + $ I * 30, rand (), $ fontColor, $ fontstyle, $ randStr );
$ Authcode. = $ randStr;
}
$ _ SESSION ['authcode'] = $ randFourStr; // compare the verification code entered by the user with that entered by the user
// 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 I <250; $ I ++ ){
Imagesetpixel ($ im, rand (0, $ x), rand (0, $ y), $ fontColor );
}
Imagepng ($ im );
Imagedestroy ($ im );
?>

Example 2

• Create a PHP file captcha_code_file.php

The Code is as follows: Copy code

// Enable the session first
Session_start ();
// Define the front-end verification code length and width
$ Image_width = 120;
$ Image_height = 40;
$ Characters_on_image = 6;
$ Font = './monofont. ttf ';

// The characters that can be used in the CAPTCHA code.
// Avoid confusing characters (l 1 and I for example)
$ Possible_letters = '23456789bcdfghjkmnpqrstvwxyz ';
$ Random_dots = 10;
$ Random_lines = 30;
$ Captcha_tex_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 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_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_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 be shown in browser widow
Imagejpeg ($ image); // showing the image
Imagedestroy ($ image); // destroying the image instance
// Set the session for verification
$ _ SESSION ['6 _ letters_code '] = $ code;

Function hexrgb ($ hexstr)
{
$ Int = hexdec ($ hexstr );

Return array ("red" => 0xFF & ($ int> 0x10 ),
"Green" => 0xFF & ($ int> 0x8 ),
"Blue" => 0xFF & $ int );
}

Index. php

<? Php
Session_start ();
If (isset ($ _ REQUEST ['submit ']) {
// Code for check server side validation
If (empty ($ _ SESSION ['6 _ letters_code ']) |
Strcasecmp ($ _ SESSION ['6 _ letters_code '], $ _ POST ['6 _ letters_code'])! = 0)
{
$ Msg = "the verification code you entered is incorrect. Please enter it again! ";
} Else {
Echo "you entered the correct one! ";
// 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 {
<A href = "http://www.bKjia. c0m"> Coinstar Money point </a> background-color: # F8F8F8;
}
</Style>

<Form action = "" method = "post" name = "form1" id = "form1">
<Table width = "400" 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>
<Td> "Id = 'captchaimg 'onclick =" refreshCaptcha (); "> <br>
<Label for = 'message'> enter the verification code: </label>
<Br>
<Input id = "6_letters_code" name = "6_letters_code" type = "text">
<Br>
If not, <a href = 'javascript: refreshCaptcha (); '> click me </a> to refresh it!
</P> </td>
</Tr>
<Tr>
<Td> & amp; nbsp; </td>
<Td> <input name = "Submit" type = "submit" onclick = "return validate ();" value = "Submit"> </td>
</Tr>
</Table>
</Form>
<Script type = 'text/javascript '>
// Define the 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

Verification code with Snowflake background

The Code is as follows: Copy code

<? Session_start ();?>
<Form method = post action = "">
<Input type = text name = number maxlength = 4>
<Input type = "submit" name = "sub">
</FORM>
<?
// Check the verification code
If (isset ($ HTTP_POST_VARS ["sub"]):
If ($ HTTP_POST_VARS ["number"]! = $ HTTP_SESSION_VARS [login_check_number] | empty ($ HTTP_POST_VARS ["number"]) {
Echo "Incorrect verification code! ";
} Else {
Echo "Verification Code passed! ";
}
Endif;
Show_source ('test. php ');
// Source code on the above page


// The source code for generating the verification code is as follows:
Show_source ('yanzhengma. php ');
?>
<? Php
Session_start ();
Session_register ("login_check_number ");

 

// I saw the verification code on chianren last night. I thought about it and used the PHP GD library to complete similar functions.
// First generate the background, and then put the generated verification code.
$ Img_height = 120; // define the length and width of the image first.
$ Img_width = 40;
If ($ HTTP_GET_VARS ["act"] = "init "){
// Srand (microtime () * 100000); // srand is not required after PHP420
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"); // generates a four-digit random number and puts it into the session
// Who can make the supplement and generate letters and numbers at the same time ?? ---- Completed by sports98

 

$ Aimg = imageCreate ($ img_height, $ img_width); // generate an image
ImageColorAllocate ($ aimg, 255,255,255); // image background color, ImageColorAllocate 1st definition color PHP considers it as background color
$ Black = ImageColorAllocate ($ aimg, 0); // define the required black


ImageRectangle ($ aimg, $ img_height-1, $ img_width-1, $ black); // enclose an image in a black rectangle first

// The following generates a snowflake background. In fact, some symbols are generated on the image.
For ($ I = 1; $ I <= 100; $ I ++) {// 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, you can see it. It's not actually a snowflake, It's just generating the * number. To make them look "chaotic, 5 colors and 6 colors", you have to make their positions, colors, and even sizes use random numbers when one of them is generated, rand () or mt_rand can be completed.
}

// The background is generated above. Now we should put the generated random number. The principle is similar to the above. Random numbers are placed in one place, and their positions, sizes, and colors are used as random numbers ~~
// To distinguish it from the background, the color here shall not exceed 200, and the color above shall not be less than 200
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 an image instead of Text
ImagePng ($ aimg); // generate the png format... Hey, the effect is pretty similar...
ImageDestroy ($ aimg );
}

?>

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.