Home >Backend Development >PHP Tutorial >A simple PHP verification code implementation code_PHP tutorial
Implementation code:
//Save the verification code in the session for global use
session_start();
$nums = "";
for($i=0;$i<4;$i++){
//Generate random numbers and convert to hexadecimal
$nums.=dechex(mt_rand(0,15));
}
//Write the verification code into session
$_SESSION['code']=$nums;
//Set the verification code length and width
$_width = 60;
$_height = 20;
//Create an image
$_img = imagecreatetruecolor($_width,$_height);
//Create a white color
$_white = imagecolorallocate($_img ,220,250,250);
//Fill the background
imagefill($_img,0,0,$_white);
//Draw 6 lines randomly
for($i=0; $i<6;$i++){
$_rnd_color = imagecolorallocate($_img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imageline($_img,mt_rand(0,$_width ),mt_rand(0,$_width),mt_rand(0,$_width),mt_rand(0,$_width),$_rnd_color);
}
//Draw snowflakes randomly
for ($i=0;$i<60;$i++){
imagestring($_img,1,mt_rand(1,$_width),mt_rand(1,$_height),"*",imagecolorallocate($_img, mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)));
}
//Output verification code
for($i=0;$i
}
//Output and destruction
header("Content-Type:image/png");
imagepng($_img);
imagedestroy($_img);
?>