php登录验证码实现
PHP 登录验证码实现
生成验证码图片
使用 PHP 的 GD 库生成验证码图片。创建一个 captcha.php 文件,用于生成验证码并存储在 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';
$captcha = '';
for ($i = 0; $i < 4; $i++) {
$captcha .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $captcha;
// 绘制干扰线
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);
}
// 绘制验证码文字
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, 'arial.ttf', $captcha[$i]);
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
在登录表单中显示验证码
在登录页面中嵌入验证码图片,并添加验证码输入框。

<form action="login.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>
验证用户输入的验证码
在 login.php 文件中,验证用户提交的验证码是否与 Session 中存储的验证码一致。

<?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('验证码错误');
}
// 验证用户名和密码的逻辑
// ...
// 清除验证码 Session
unset($_SESSION['captcha']);
echo '登录成功';
}
?>
安全性增强
为提高安全性,可以采取以下措施:
- 设置验证码过期时间,例如 5 分钟后失效。
- 限制验证码尝试次数,防止暴力破解。
- 使用更复杂的验证码生成逻辑,如扭曲文字、背景噪声等。
验证码自动刷新
通过 JavaScript 实现点击验证码图片自动刷新功能。
document.querySelector('img[alt="验证码"]').addEventListener('click', function() {
this.src = 'captcha.php?' + Math.random();
});
注意事项
- 确保服务器已安装 GD 库。
- 验证码字体文件(如
arial.ttf)需放置在正确路径。 - 生产环境中应使用更安全的 Session 管理方式。
- 验证码生成逻辑可根据需求调整复杂度。






