php实现图形验证码
生成验证码图像
使用 PHP 的 GD 库创建画布并生成随机字符串作为验证码内容。设置背景色、文字颜色和干扰元素(如噪点、线条)。
// 创建画布
$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
session_start();
$_SESSION['captcha'] = $code;
// 绘制文字
for ($i = 0; $i < 4; $i++) {
$textColor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
imagettftext($image, rand(18, 22), rand(-30, 30), 10 + $i * 30, 30, $textColor, 'path/to/font.ttf', $code[$i]);
}
// 添加干扰元素
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);
}
for ($i = 0; $i < 5; $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);
}
输出图像
设置响应头为图像类型,并输出图像内容。完成后销毁图像资源释放内存。
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
验证码校验
在表单提交时,将用户输入的验证码与 Session 中存储的值进行比对。
session_start();
if (isset($_POST['captcha']) && isset($_SESSION['captcha'])) {
if (strtolower($_POST['captcha']) === strtolower($_SESSION['captcha'])) {
echo '验证码正确';
} else {
echo '验证码错误';
}
unset($_SESSION['captcha']); // 清除 Session 中的验证码
}
注意事项
- 字体文件需使用
imagettftext()支持的格式(如.ttf),需提供正确路径 - 验证码生成和校验需在同一个 Session 上下文中
- 干扰元素的数量和复杂度可根据需求调整
- 生产环境建议使用更安全的随机数生成方式(如
random_int())







