Home  >  Article  >  Backend Development  >  PHP generates graphic verification code program with background_PHP tutorial

PHP generates graphic verification code program with background_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:47:431044browse

In the past, we used PHP to generate verification codes without background or with the same color background, but this kind of verification is easy for machines to recognize. Let me introduce some examples of generating graphic verification codes with background.

Example

1. Generate a png picture
2. Set the background color for the picture
3. Set font color and style
4. Generate a 4-digit random verification code
5. Adjust the rotation angle and position of each generated character and draw it on the png image
6. Add noise and interference lines to prevent the registration machine from analyzing the original image for malicious registration
7. Output pictures
8. Release the memory occupied by the picture
authcode.php file

Code

The code is as follows Copy code
代码如下 复制代码
session_start ();
header ( 'Content-type: image/png' );
//创建图片
$im = imagecreate($x=130,$y=45 );
$bg = imagecolorallocate($im,rand(50,200),rand(0,155),rand(0,155)); //第一次对 imagecolorallocate() 的调用会给基于调色板的图像填充背景色
$fontColor = imageColorAllocate ( $im, 255, 255, 255 ); //字体颜色
$fontstyle = 'rock.ttf'; //字体样式,这个可以从c:windowsFonts文件夹下找到,我把它放到和authcode.php文件同一个目录,这里可以替换其他的字体样式
//产生随机字符
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;//用户和用户输入的验证码做比较
//干扰线
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);
}
//干扰点
for ($i=0;$i<250;$i++){
imagesetpixel($im,rand(0,$x),rand(0,$y),$fontColor);
}
imagepng($im);
imagedestroy($im);
?>
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() will fill the palette-based image with the background color $fontColor = imageColorAllocate ($im, 255, 255, 255); //Font color $fontstyle = 'rock.ttf'; //Font style, this can be found in the c:windowsFonts folder. I put it in the same directory as the authcode.php file. You can replace other font styles here ​​​​ //Generate random characters for($i = 0; $i < 4; $i ++) {<🎜> $randAsciiNumArray = array (rand(48,57),rand(65,90));<🎜>                                                                                                                                                                                                                                                                                 Imagettftext($im,30,rand(0,20)-rand(0,25),5+$i*30,rand(30,35),$fontColor,$fontstyle,$randStr);<🎜>                        $authcode                                                                                             }<🎜> $ _Session ['Authcode'] = $ Randfourstr; // The verification code entered by the user and the user to compare <🎜> ​​​​ //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

The code is as follows Copy code

//First open the session
session_start();
//Define the length & width of the verification code displayed in the front desk
$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_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 noise colors 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 up session and do 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);
}

Display verification code page index.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 re-enter!";
}else{
echo "What you entered is correct!";
// Captcha verification is Correct. Final Code Execute here!
}

?>







                                                                                                                                                                                                                                             


                                                                                                                                alone


       

            
                                                                                                    
                                                                                          If you can’t see it, please Click me to refresh it!
                                                                                                 






Example 3

Verification code with snowflake background

The code is as follows Copy code






//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 "The check code is incorrect!" ;
}else{
echo "Verification code passed!";
}
endif;
show_source('test.php');
//Source code of the above page


//The following is the source code for generating verification code
show_source('YanZhengMa.php');
?>
session_start();
session_register("login_check_number");

//I saw the verification code effect on chianren last night, so I thought about it and used PHP’s GD library to complete a similar function
//Generate the background first, then put the generated verification code
$img_height=120; //First define the length and width of the image
$img_width=40;
if($HTTP_GET_VARS["act"]== "init"){
//srand(microtime() * 100000);//After PHP420, srand is not necessary
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 a 4-digit random number and put it into the session
//Who can add something that can generate letters and numbers at the same time? ? ----Complete by sports98

$aimg = imageCreate($img_height,$img_width); //Generate image
ImageColorAllocate($aimg, 255,255,255); //The background color of the picture, the first time ImageColorAllocate defines the color, PHP considers it as the background color
$black = ImageColorAllocate($aimg, 0,0,0); //Define the required black


ImageRectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//First create a black rectangle to surround the image

//It’s time to generate the snowflake background, which is actually to generate some symbols on the picture
for ($i=1; $i<=100; $i++) { //Test with 100 first


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 see, it’s not actually a snowflake, it’s just an * sign. In order to make them look "messy and colorful", you have to use random numbers for their position, color, and even size when generating them one by one. This can be done with rand() or mt_rand.
}

//The background is generated above, now it’s time to put the generated random numbers. The principle is similar to the above. Random numbers are placed one by one, and their positions, sizes, and colors are all random numbers~~
//In order to distinguish it from the background, the color here should not exceed 200, and the color above should not be less than 200
for ($i=0;$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 png format. . . Hehe, the effect is quite similar. . .
ImageDestroy($aimg);
}

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632839.htmlTechArticleIn the past, we used PHP to generate verification codes without background or with the same color background, but this kind of verification is easy It has been recognized by the machine. Now I will introduce some graphic verification codes with background...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn