验证码的生成
<?php
session_start();
$charset = '0123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcvbnmasdfghjkpiuytrewq';
$randomString = '';
$length = 6;
$charsetLength = strlen($charset) - 1;
for ($i = 0; $i < $length; $i++) {
$randomString .= $charset[random_int(0, $charsetLength)];
}
$_SESSION['captcha'] = $randomString;
$image = imagecreatetruecolor(120, 40);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 120, 40, $bgColor);
imagestring($image, 5, 40, 10, $randomString, $textColor);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
验证码的调用
<div id="popup" class="popup">
<div class="popup-inner">
<center><h3>用户注册</h3></center>
<span class="button-close" onclick="closePopup()">×</span>
<form id="joinForm" action="sub.php" method="POST">
<div class="form-group">
<label for="username">账号:</label>
<input type="text" id="username" name="username" placeholder="请输入账号" required>
</div>
<div class="form-group">
<label for="userpass">密码:</label>
<input type="pass" id="userpass" name="userpass" placeholder="请输密码" required>
</div>
<div class="form-group">
<label for="captcha">验证码:<img class="ue-image" src="yzm.php"/></label>
<input type="text" id="captcha" name="captcha" placeholder="请输入验证码" required>
</div>
<div class="form-group">
<div class="button-group">
<button type="submit">提交</button>
</div>
</div>
</form>
</div>
</div>
验证码的验证
<?php
session_start();
if(!empty($_POST)){
$username = $_POST['username'];
$userpass = $_POST['userpass'];
$captcha = $_POST['captcha'];
if (!preg_match('/^[A-Za-z0-9]+$/', $captcha)) {
echo '<script>alert("验证码不正确!"); window.location.href = "index.php";</script>';
exit;
}
if($captcha!=$_SESSION['captcha']){
echo '<script>alert("验证码不正确!"); window.location.href = "index.php";</script>';
exit;
}else{
}
}
?>