PHP Realizes Login Verification Code Verification Function
- 2021-10-13 06:45:11
- OfStack
The verification code is realized by using SESSION function in PHP.
Declare a function at the top
session_start();
Tell the server that we want to use the function.
session_start();
Next, we use the code realized by verification code. Here, use the code of English numbers as an example.
$image = imagecreatetruecolor(100, 30); // Create 1 A 100 × 30 Canvas of
$white = imagecolorallocate($image,255,255,255);// White
imagefill($image,0,0,$white);// Covered with black canvas
Then, before the implementation of the verification code, a null variable is declared to store the verification code.
$session = ""; // Null variable , store the verification code
for($i=0;$i<4;$i++){
$size = 6;
$x = $i*25+mt_rand(5,10);
$y = mt_rand(5,10);
$sizi_color = imagecolorallocate($image,mt_rand(80,220),mt_rand(80,220),mt_rand(80,220));
$char = join("",array_merge(range('a','z'),range('A','Z'),range(0,9)));
$char = str_shuffle($char);
$char = substr($char,0,1);
imagestring($image,$size,$x,$y,$char,$sizi_color);
$session .= $char ; // Put every verification code 1 Assign a value to a variable
}
$_SESSION['session'] = $session; // The value of this variable is equal to the value entered by the user
for($k=0;$k<200;$k++){
$rand_color = imagecolorallocate($image,mt_rand(50,200),mt_rand(50,200),mt_rand(50,200));
imagesetpixel($image,mt_rand(1,99),mt_rand(1,29),$rand_color);
}
for($n=0;$n<5;$n++){
$line_color = imagecolorallocate($image,mt_rand(80,220),mt_rand(80,220),mt_rand(80,220));
imageline($image,mt_rand(1,99),mt_rand(1,29),mt_rand(1,99),mt_rand(1,29),$line_color);
}
header('content-type:image/png');// Set the file output format
imagepng( $image ); // With png Format output $image Image
imagedestroy( $image ); // Destroy images
Use POST to receive the verification code. The strtolower function makes the server case insensitive. This can effectively reduce the input error rate of users.
if(isset($_POST['session'])){
session_start();
if(strtolower($_POST['session'])==strtolower($_SESSION['session'])){
echo'<font color="#0000CC"> Enter correctly </form>';
}else{
echo '<font color="#CC0000"><b> Input error </b></font>';
}
exit();
}
Here is the page code for HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title> Confirm verification code </title>
</head>
<body>
<form method="post" action="./tushu.php">
<p> Verification code picture :<img id="img" border="1" src="http://localhost//xxx.php" width="100" height="30"></p>
<a href="javascript:void(0)" rel="external nofollow" onclick="document.getElementById('img').src='http://localhost//xxx.php'"> Can't see clearly? Change 1 A </a>
<p> Please enter the verification code in the picture: <input type="text" name="session" value=""/></p>
<p><input type="submit" value=" Submit " style="padding:6px 10px;"></p>
</form>
</body>
</html>
Summarize