php实现变色验证码
实现变色验证码的步骤
生成随机验证码字符串
使用PHP的rand或mt_rand函数生成随机字符串,通常为4-6位的字母数字组合:
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$length = 4;
$code = substr(str_shuffle($chars), 0, $length);
创建图像资源
使用GD库创建画布并设置背景色:
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
添加干扰元素
绘制干扰线和噪点增强安全性:

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);
}
for ($i = 0; $i < 200; $i++) {
$color = imagecolorallocate($image, rand(150, 250), rand(150, 250), rand(150, 250));
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
绘制变色文字
关键变色效果通过循环改变每个字符颜色实现:
for ($i = 0; $i < $length; $i++) {
$color = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
$x = 20 + $i * 25;
$y = rand(15, 25);
imagettftext($image, 20, rand(-15, 15), $x, $y, $color, 'path/to/font.ttf', $code[$i]);
}
输出并存储验证码

输出图像前将验证码存入Session:
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
$_SESSION['captcha'] = $code;
增强变色效果的技巧
动态颜色变化算法 使用HSV色彩空间转换实现平滑变色:
$hue = rand(0, 360);
$saturation = 80;
$value = 90;
list($r, $g, $b) = hsvToRgb($hue, $saturation, $value);
字体选择建议
推荐使用等宽字体如Courier New或Monospace,确保字符位置对齐
抗锯齿处理 启用抗锯齿提升显示质量:
imageantialias($image, true);
完整示例代码
session_start();
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = substr(str_shuffle($chars), 0, 4);
$image = imagecreatetruecolor(120, 40);
imagefill($image, 0, 0, imagecolorallocate($image, 255, 255, 255));
// 添加干扰元素
for ($i = 0; $i < 5; $i++) {
imageline($image, rand(0, 120), rand(0, 40), rand(0, 120), rand(0, 40),
imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200)));
}
// 绘制变色字符
for ($i = 0; $i < 4; $i++) {
imagettftext($image, 20, rand(-15, 15), 20 + $i * 25, rand(25, 35),
imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150)),
'arial.ttf', $code[$i]);
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
$_SESSION['captcha'] = $code;
注意事项
- 需要确保服务器安装GD库
- 字体文件路径需正确配置
- 验证码复杂度可调整干扰元素数量控制
- 建议添加表单提交后的验证逻辑






