php实现图形验证码
实现图形验证码的基本步骤
使用 PHP 生成图形验证码主要依赖 GD 库或 Imagick 扩展。以下是基于 GD 库的实现方法。
创建画布并生成随机字符串
初始化画布并生成随机验证码字符串,通常包含数字和字母组合。
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;
添加干扰元素
为增强安全性,可添加干扰线或干扰点,防止机器识别。
for ($i = 0; $i < 6; $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 < 100; $i++) {
$pixelColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $pixelColor);
}
绘制验证码文字
将随机生成的验证码字符串绘制到画布上,可调整字体、颜色和位置。
$fontFile = 'path/to/font.ttf'; // 替换为实际字体文件路径
for ($i = 0; $i < strlen($code); $i++) {
$textColor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, 20, rand(-10, 10), 10 + $i * 30, 30, $textColor, $fontFile, $code[$i]);
}
输出验证码图像
设置响应头并输出图像,确保浏览器正确解析为图片格式。
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
验证用户输入
在表单提交时,比对用户输入与 Session 中存储的验证码。

session_start();
if (strtolower($_POST['captcha']) === strtolower($_SESSION['captcha'])) {
echo '验证码正确';
} else {
echo '验证码错误';
}
注意事项
- 确保服务器已安装 GD 库(可通过
phpinfo()检查)。 - 字体文件需可读,若无需特殊字体可用
imagestring()替代imagettftext()。 - 生产环境建议增加更多干扰措施(如扭曲文字、背景噪点)。
- 验证码生成后应立即销毁 Session 中的旧值,防止重复使用。






