php实现变色验证码
生成随机验证码字符串
使用rand()或mt_rand()生成随机数字/字母组合,例如4-6位字符。可结合array_merge()合并数字和字母数组,再通过shuffle()打乱顺序。
$chars = array_merge(range(0,9), range('a','z'), range('A','Z'));
shuffle($chars);
$code = implode('', array_slice($chars, 0, 6)); // 取6位
创建画布并设置背景
使用imagecreatetruecolor()创建指定大小的画布,用imagefill()填充背景色(通常为浅色)。
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 240, 240, 240);
imagefill($image, 0, 0, $bgColor);
添加干扰元素
通过循环绘制随机干扰线、点或弧线,增加识别难度。颜色使用随机值生成。
for ($i=0; $i<5; $i++) {
$color = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
imageline($image, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $color);
}
输出变色验证码文字
每个字符使用不同的随机颜色,通过imagettftext()或imagestring()写入画布。建议使用TTF字体增强效果。
$font = 'path/to/font.ttf'; // 需准备字体文件
for ($i=0; $i<strlen($code); $i++) {
$color = imagecolorallocate($image, rand(0,150), rand(0,150), rand(0,150));
imagettftext($image, 20, rand(-30,30), 10+$i*20, 30, $color, $font, $code[$i]);
}
输出图像并销毁资源
通过header()设置MIME类型后,用imagepng()输出图像,最后调用imagedestroy()释放内存。
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
存储验证码用于校验
将生成的验证码存入$_SESSION,便于后续表单提交时比对。
session_start();
$_SESSION['captcha'] = $code;
注意事项
- 字体文件需提前放置到项目目录
- 确保PHP已安装GD库(通过
phpinfo()检查) - 验证码复杂度可通过调整干扰元素数量、字符扭曲程度控制
- 实际使用时应结合表单提交的Session验证逻辑







