php实现变色验证码
使用PHP生成变色验证码
PHP生成变色验证码主要涉及GD库的使用,通过随机颜色和干扰元素增强安全性。以下是实现变色验证码的完整代码示例:
<?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['captcha'] = $code;
// 绘制文字(每个字符不同颜色)
for ($i = 0; $i < 4; $i++) {
$color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, 20, rand(-30, 30), 10 + $i * 30, 30, $color, 'arial.ttf', $code[$i]);
}
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$color = 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), $color);
}
// 添加噪点
for ($i = 0; $i < 200; $i++) {
$color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
// 输出图像
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
验证码使用说明
-
将上述代码保存为captcha.php文件
-
在HTML页面中通过img标签引用验证码:
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()"> -
表单提交时验证:
session_start(); if ($_POST['captcha'] !== $_SESSION['captcha']) { die('验证码错误'); }
增强安全性建议
- 增加字体倾斜角度范围,使字符变形更明显
- 使用更复杂的字符集,如加入特殊符号
- 调整验证码长度(修改循环次数)
- 添加背景干扰纹理或图案
- 限制验证码尝试次数,防止暴力破解
注意事项
- 确保服务器已安装GD库
- 需要准备TrueType字体文件(如arial.ttf)
- 验证码会话应设置较短有效期
- 考虑添加点击刷新功能(示例中已实现)
- 生产环境建议使用专业验证码解决方案
此实现通过随机颜色、干扰线和噪点有效防止OCR识别,同时字符变形增强了安全性。可根据实际需求调整参数获得不同效果。







