Home > Article > Backend Development > Detailed tutorial on generating verification code in php_PHP tutorial
This article provides a detailed tutorial on generating verification codes in PHP. The first part is about generating the core verification code, and the second part is a method of generating and calling it.
//header("content-type:image/png");
$num ='1234';
$imagewidth=60;
$imageheight=18;$numimage = imagecreate($imagewidth,$imageheight);
imagecolorallocate($numimage,240,240,240);
for($i=0;$i$x = mt_rand(1,8)+$imagewidth*$i/4;
$y = mt_rand(1,$imageheight/4);
$color=imagecolorallocate($numimage,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150));
imagestring($numimage,5,$x,$y,$num[$i],$color);
}for($i=0;$i<200;$i++){
$randcolor=imagecolorallocate($numimage,rand(200,255),rand(200,255),rand(200,255));
imagesetpixel($numimage,rand()%70,rand()%20,$randcolor);
}
imagepng($numimage);
imagedestroy($numimage);
?>
Let’s take a look at an example of generating a verification code
//Generate verification code image
session_start();
header("content-type: image/png");
srand((double)microtime()*1000000);
$roundnum=rand(1000,9999);
//Save the random number into the session for later use
$_session["sessionround"]=$roundnum;
$im = imagecreate(58,28);
$red = imagecolorallocate($im, 255,0,0);
$blue = imagecolorallocate($im, 0,255,0);
//Local filling, equivalent to background
imagefill($im,68,30,$red);
//Draw the four-digit integer verification code into the picture
imagestring($im, 5, 10, 8, $roundnum, $blue);
for($i=0;$i<50;$i++) //Add interference pixels
{
imagesetpixel($im, rand()%70, rand()%30, $black);
}
imagepng($im);
imagedestroy($im);
?>
html call method
Verification code