php实现验证码注册
生成验证码
使用PHP的GD库生成验证码图片,并将验证码存储在Session中以便后续验证。以下是一个简单的验证码生成代码示例:
<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
$font = 'path/to/font.ttf';
for ($i = 0; $i < 4; $i++) {
$textColor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, 20, rand(-30, 30), 10 + $i * 30, 30, $textColor, $font, $code[$i]);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
前端显示验证码
在HTML表单中添加验证码图片和输入框:

<form action="register.php" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
<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>
验证验证码
在注册处理页面验证用户输入的验证码是否匹配:

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$userCaptcha = $_POST['captcha'];
if (empty($_SESSION['captcha']) || strtolower($userCaptcha) !== strtolower($_SESSION['captcha'])) {
die('验证码错误');
}
// 验证通过,继续注册流程
unset($_SESSION['captcha']);
// 保存用户数据等操作
echo '注册成功';
}
?>
安全增强措施
为了提高验证码的安全性,可以采取以下措施:
- 增加干扰线和干扰点
- 使用更复杂的字体和扭曲效果
- 限制验证码尝试次数
- 设置验证码有效期
// 增加干扰线示例
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
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验证码注册功能,可以根据实际需求进行调整和扩展。






