php实现动态验证码
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);
// 生成随机验证码
$code = '';
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
// 存储验证码到 Session
$_SESSION['captcha'] = $code;
// 绘制验证码文字
for ($i = 0; $i < strlen($code); $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', $code[$i]);
}
// 添加干扰线
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);
}
// 输出图片
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
前端显示验证码
在 HTML 页面中嵌入验证码图片,并允许用户点击刷新验证码。
<!DOCTYPE html>
<html>
<head>
<title>验证码示例</title>
</head>
<body>
<form action="verify.php" method="post">
<img src="captcha.php" id="captcha" onclick="refreshCaptcha()" style="cursor: pointer;">
<input type="text" name="captcha" placeholder="输入验证码">
<button type="submit">提交</button>
</form>
<script>
function refreshCaptcha() {
document.getElementById('captcha').src = 'captcha.php?t=' + new Date().getTime();
}
</script>
</body>
</html>
验证用户输入
在服务器端验证用户输入的验证码是否与 Session 中存储的验证码一致。

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$userCaptcha = isset($_POST['captcha']) ? trim($_POST['captcha']) : '';
$sessionCaptcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : '';
if (empty($userCaptcha) || empty($sessionCaptcha)) {
die('验证码不能为空');
}
if (strtolower($userCaptcha) === strtolower($sessionCaptcha)) {
echo '验证码正确';
} else {
echo '验证码错误';
}
// 清除 Session 中的验证码
unset($_SESSION['captcha']);
}
?>
注意事项
- 确保服务器已安装 GD 库,否则无法生成图片。
- 验证码图片生成后应立即销毁,避免资源占用。
- 验证码字符串建议使用大小写混合或数字字母组合,增强安全性。
- 验证码图片可添加干扰线或噪点,防止机器识别。
通过以上方法,可以快速实现 PHP 动态验证码功能,提升网站安全性。






