php实现验证码注册
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 = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
$textColor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 30, 12, $code, $textColor);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
显示验证码图片
在 HTML 表单中嵌入验证码图片,通过 img 标签调用生成验证码的 PHP 文件。
<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>
验证用户输入
在注册处理逻辑中,比对用户输入的验证码与 session 中存储的验证码是否一致。

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$userCaptcha = $_POST['captcha'];
if (empty($userCaptcha) || $userCaptcha !== $_SESSION['captcha']) {
die('验证码错误');
}
// 验证通过后,继续处理注册逻辑
// 例如保存用户信息到数据库
// ...
echo '注册成功';
}
?>
刷新验证码
为了提升用户体验,可以通过 JavaScript 实现点击验证码图片刷新功能。
document.querySelector('img[alt="验证码"]').addEventListener('click', function() {
this.src = 'captcha.php?' + Math.random();
});
安全性增强
为提高安全性,可以对验证码进行扭曲、添加干扰线等处理,增加机器识别的难度。
// 在 captcha.php 中添加干扰线和扭曲效果
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);
}
// 扭曲效果
$distortion = rand(1, 3);
for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
$newX = $x + sin($y / 10) * $distortion;
$newY = $y + cos($x / 10) * $distortion;
if ($newX < $width && $newY < $height && $newX >= 0 && $newY >= 0) {
$color = imagecolorat($image, $x, $y);
imagesetpixel($image, $newX, $newY, $color);
}
}
}
通过以上步骤,可以实现一个基本的验证码注册功能。验证码的有效期可以通过设置 session 过期时间来控制,进一步提升安全性。






