php实现动态验证码
使用 PHP 生成动态验证码
PHP 可以通过 GD 库或 Imagick 扩展生成动态验证码图片,通常包括随机字符、干扰线和噪点以提高安全性。
核心步骤
安装或启用 GD 库(通常 PHP 默认已安装),在 php.ini 中取消注释 extension=gd。
创建验证码生成脚本 captcha.php:
<?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 = '';
$length = 4;
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
$font = 'path/to/font.ttf'; // 使用真实字体文件路径
for ($i = 0; $i < $length; $i++) {
$color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, rand(18, 22), rand(-30, 30), 20 + $i * 25, 30, $color, $font, $code[$i]);
}
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$color = 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), $color);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
前端调用验证码
在 HTML 表单中显示验证码图片并设置自动刷新:
<img src="captcha.php" id="captcha" onclick="refreshCaptcha()">
<input type="text" name="captcha_code" required>
<script>
function refreshCaptcha() {
document.getElementById('captcha').src = 'captcha.php?' + Math.random();
}
</script>
服务器端验证
表单提交后验证用户输入:
session_start();
if ($_POST['captcha_code'] !== $_SESSION['captcha']) {
die('验证码错误');
}
// 验证通过后清除session中的验证码
unset($_SESSION['captcha']);
安全增强措施
使用更复杂的字符组合,避免使用易混淆字符(如 0 和 O)。
增加验证码失效时间:
$_SESSION['captcha_time'] = time();
// 验证时检查
if (time() - $_SESSION['captcha_time'] > 300) {
die('验证码已过期');
}
考虑添加更多干扰元素,如扭曲变形、背景噪点等。对于更高安全性需求,可以使用 Composer 安装专业验证码库如 "gregwar/captcha"。







