php实现验证码注册
生成验证码图片
使用 PHP 的 GD 库生成验证码图片,创建一个包含随机字符的图像。以下代码示例生成一个 4 位数字验证码:
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$chars = '0123456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
$char = $chars[rand(0, strlen($chars) - 1)];
$code .= $char;
$textColor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, 20, rand(-30, 30), 10 + $i * 30, 30, $textColor, 'arial.ttf', $char);
}
$_SESSION['captcha'] = $code;
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
前端显示验证码
在 HTML 表单中添加验证码图片显示区域和输入框:

<form action="register.php" method="post">
<label for="captcha">验证码:</label>
<input type="text" id="captcha" name="captcha" required>
<img src="captcha.php" alt="验证码" onclick="this.src='captcha.php?'+Math.random()">
<button type="submit">注册</button>
</form>
验证码校验
在注册处理页面验证用户输入的验证码是否匹配:

session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$userCaptcha = $_POST['captcha'] ?? '';
$trueCaptcha = $_SESSION['captcha'] ?? '';
if (empty($userCaptcha) || $userCaptcha !== $trueCaptcha) {
die('验证码错误');
}
// 验证码正确,继续处理注册逻辑
// ...
// 验证成功后销毁验证码
unset($_SESSION['captcha']);
}
增强安全性措施
为提升验证码安全性,可以采取以下措施:
- 使用更复杂的字符组合(字母+数字)
- 添加干扰线和噪点
- 限制验证码尝试次数
- 设置验证码有效期
// 添加干扰线示例
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
验证码自动刷新
通过 JavaScript 实现点击验证码图片自动刷新:
document.querySelector('img[alt="验证码"]').addEventListener('click', function() {
this.src = 'captcha.php?' + Math.random();
});
以上实现方案提供了完整的 PHP 验证码注册流程,包括生成、显示、验证和安全性增强措施。可以根据实际需求调整验证码长度、复杂度和样式。






