Home >Backend Development >PHP Tutorial >A beautiful PHP image verification code example_PHP tutorial
1. Display effect
2. The code is as follows
$imgwidth =100; //Picture width
$imgheight =40; //Picture height
$codelen =4; //Verification code length
$fontsize =20; //Font size
$charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';
$font = 'Fonts/segoesc.ttf';
$im=imagecreatetruecolor($imgwidth,$imgheight);
$while=imageColorAllocate($im,255,255,255);
imagefill($im,0,0,$while); //Fill the image
//Get the string
$authstr='';
$_len = strlen($charset)-1;
for ($i=0;$i<$codelen;$i++) {
$authstr .= $charset[mt_rand(0,$_len)];
}
session_start();
$_SESSION['scode']=strtolower($authstr);//Convert all to lowercase, mainly to avoid case sensitivity
//Draw random points, which have been changed to stars
for ($i=0;$i<$imgwidth;$i++){
$randcolor=imageColorallocate($im,mt_rand(200,255) ,mt_rand(200,255),mt_rand(200,255));
imagestring($im,mt_rand(1,5), mt_rand(0,$imgwidth),mt_rand(0,$imgheight), '*',$randcolor) ;
//imagesetpixel($im,mt_rand(0,$imgwidth),mt_rand(0,$imgheight),$randcolor);
}
//Draw lines randomly, number of lines = number of characters ( Whatever)
for($i=0;$i<$codelen;$i++)
{
$randcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255) );
imageline($im,0,mt_rand(0,$imgheight),$imgwidth,mt_rand(0,$imgheight),$randcolor);
}
$_x=intval($imgwidth/$codelen); //Calculate character distance $randcolor=imagecolorallocate($im,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150)); } //Generate image
$_y=intval($imgheight*0.7); //Characters are displayed at 70% of the image
for($ i=0;$i
//imagestring($im,5,$j,5,$imgstr[$i] ,$color3);
// imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
imagettftext($ im,$fontsize,mt_rand(-30,30),$i*$_x+3,$_y,$randcolor,$font,$authstr[$i]);
header("content-type:image/PNG");
imagePNG($im);
imageDestroy($im);