Study Address: http://www.imooc.com/video/2458
<?PHP/** * Generate verification code * @param int $type * @param int $length * @return string*/functionBuildrandomstring ($type=1,$length=4){ if($type= = 1) { $chars=Join( "",Range(0, 9 ) ); } ElseIf($type= = 2) { $chars=Join( "",Array_merge(Range("A", "Z"),Range("A", "Z" ) ) ); } ElseIf($type= = 3) { $chars=Join( "",Array_merge(Range("A", "Z"),Range("A", "Z"),Range(0, 9 ) ) ); } if($length>strlen($chars )) { Exit("String length is not enough" ); } $chars=Str_shuffle($chars ); return substr($chars, 0,$length );}//Verify code via GD libraryfunctionVerifyimage ($type=1,$length=4,$pixel=0,$line=0,$sess _name= "Verify"){ Session_Start(); //Create a canvas $width= 80; $height= 28; $image= Imagecreatetruecolor ($width,$height ); $white= Imagecolorallocate ($image, 255, 255, 255 ); $black= Imagecolorallocate ($image, 0, 0, 0 ); //fill the canvas with filled rectanglesImagefilledrectangle ($image, 1, 1,$width-2,$height-2,$white ); $chars= Buildrandomstring ($type,$length ); $_session[$sess _name] =$chars; //$fontfiles = Array ("Msyh. TTF "," MSYHBD. TTF "," Simli. TTF "," SimSun. TTC "," simyou. TTF "," stzhongs. TTF "); $fontfiles=Array("Simyou. TTF " ); //because the font file is larger, just keep a font, if the students need to add their own fonts, fonts in your computer's Fonts folder, directly run the input fonts will be able to see the corresponding font for($i= 0;$i<$length;$i++) { $size=Mt_rand(14, 18 ); $angle=Mt_rand(-15, 15 ); $x= 5 +$i*$size; $y=Mt_rand(20, 26 ); $fontfile= ".. /fonts/".$fontfiles[Mt_rand* R,Count($fontfiles)-1 )]; $color= Imagecolorallocate ($image,Mt_rand(50, 90),Mt_rand(80, 200),Mt_rand(90, 180 ) ); $text=substr($chars,$i, 1 ); Imagettftext ($image,$size,$angle,$x,$y,$color, "",$text); } if($pixel) { for($i= 0;$i< 50;$i++) {Imagesetpixel ($image,Mt_rand* R,$width-1),Mt_rand* R,$height-1),$black ); } } if($line) { for($i= 1;$i<$line;$i++) { $color= Imagecolorallocate ($image,Mt_rand(50, 90),Mt_rand(80, 200),Mt_rand(90, 180 ) ); Imageline ($image,Mt_rand* R,$width-1),Mt_rand* R,$height-1),Mt_rand* R,$width-1),Mt_rand* R,$height-1),$color ); } } Header("Content-type:image/gif" ); Imagegif ($image ); Imagedestroy ($image );}
PHP Verification Code