代码:
<?php
// 1. 开启会话
session_start();
// 2. 定义字符集和长度
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$captcha_text = '';
$captcha_code_length = 6;
// 3. 生成随机验证码
for($i = 0; $i < $captcha_code_length; $i++) {
$captcha_text .= $characters[rand(0, strlen($characters) - 1)];
}
// 4. 存储到会话
$_SESSION['captcha'] = $captcha_text;
// 5. 创建图像
$image_width = 150;
$image_height = 50;
$image = imagecreatetruecolor($image_width, $image_height);
// 6. 分配颜色
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
$line_color = imagecolorallocate($image, 64, 64, 64);
// 7. 填充背景
imagefilledrectangle($image, 0, 0, $image_width, $image_height, $background_color);
// 8. 添加文字
$font_size = 5;
$x = (imagesx($image) - imagefontwidth($font_size) * strlen($captcha_text)) / 2;
$y = (imagesy($image) - imagefontheight($font_size)) / 2 + imagefontheight($font_size) / 2;
imagestring($image, $font_size, $x, $y, $captcha_text, $text_color);
// 9. 添加干扰
for($i = 0; $i < 10; $i++) {
imageline($image, rand(0, $image_width), rand(0, $image_height),
rand(0, $image_width), rand(0, $image_height), $line_color);
imagesetpixel($image, rand(0, $image_width), rand(0, $image_height), $line_color);
}
// 10. 输出图像
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>PHP使用GD库生成图片验证码详细教程
一、准备工作
1. 检查GD库是否安装
在开始之前,需要确保PHP环境中已经安装了GD库扩展1。
<?php
if(function_exists('gd_info')) {
echo "GD库已安装";
print_r(gd_info());
} else {
echo "GD库未安装";
}
?>gd_info()函数返回一个关联数组,包含GD库的安装信息:
GD Version: GD库版本FreeType Support: 是否支持FreeType字体GIF Read Support: 是否支持读取GIFGIF Create Support: 是否支持创建GIFJPEG Support: 是否支持JPEGPNG Support: 是否支持PNGWBMP Support: 是否支持WBMPXPM Support: 是否支持XPMXBM Support: 是否支持XBMWebP Support: 是否支持WebP
2. 安装GD库
如果未安装GD库,需要根据操作系统进行安装:
Ubuntu/Debian:
sudo apt-get install php-gdCentOS/RHEL:
sudo yum install php-gdWindows: 编辑php.ini文件,取消
extension=gd前面的注释
安装后需要重启Web服务器。
二、生成验证码的完整步骤
1. 创建PHP文件并开启会话
验证码通常需要存储在会话中以便后续验证。
<?php // 开启会话 session_start();
2. 定义验证码字符集和长度
验证码通常由数字、字母或它们的组合构成1。
// 验证码字符集 - 包含数字和小写字母 $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $captcha_text = ''; $captcha_code_length = 6; // 验证码长度
3. 生成随机验证码字符串
使用循环从字符集中随机选取字符组成验证码1。
// 生成随机验证码文本
for($i = 0; $i < $captcha_code_length; $i++) {
$captcha_text .= $characters[rand(0, strlen($characters) - 1)];
}4. 存储验证码到会话
将生成的验证码存入$_SESSION以便后续验证1。
// 存储验证码文本到会话中 $_SESSION['captcha'] = $captcha_text;
5. 创建图像资源
使用imagecreatetruecolor()函数创建一个真彩色图像2。
// 图像尺寸 $image_width = 150; $image_height = 50; // 创建图像资源 $image = imagecreatetruecolor($image_width, $image_height);
imagecreatetruecolor()函数参数:
width: 图像宽度(像素)height: 图像高度(像素)
返回一个图像资源标识符,失败时返回FALSE。
6. 分配颜色
使用imagecolorallocate()为图像分配颜色2。
// 分配颜色 $background_color = imagecolorallocate($image, 255, 255, 255); // 白色背景 $text_color = imagecolorallocate($image, 0, 0, 0); // 黑色文字 $line_color = imagecolorallocate($image, 64, 64, 64); // 灰色干扰线
imagecolorallocate()函数参数:
image: 由图像创建函数返回的图像资源red: 红色成分(0-255)green: 绿色成分(0-255)blue: 蓝色成分(0-255)
返回一个颜色标识符,失败时返回FALSE。
7. 填充背景色
使用imagefilledrectangle()填充图像背景2。
// 填充背景颜色 imagefilledrectangle($image, 0, 0, $image_width, $image_height, $background_color);
imagefilledrectangle()函数参数:
image: 图像资源x1: 左上角x坐标y1: 左上角y坐标x2: 右下角x坐标y2: 右下角y坐标color: 填充颜色
8. 添加验证码文字
使用imagestring()将验证码文字添加到图像上1。
// 添加文字到图片 $font_size = 5; $x = (imagesx($image) - imagefontwidth($font_size) * strlen($captcha_text)) / 2; $y = (imagesy($image) - imagefontheight($font_size)) / 2 + imagefontheight($font_size) / 2; imagestring($image, $font_size, $x, $y, $captcha_text, $text_color);
imagestring()函数参数:
image: 图像资源font: 字体(1-5是内置字体)x: 起始x坐标y: 起始y坐标string: 要写入的字符串color: 文本颜色
辅助函数:
imagesx(): 获取图像宽度imagesy(): 获取图像高度imagefontwidth(): 获取字体宽度imagefontheight(): 获取字体高度
9. 添加干扰元素
为了增加安全性,可以添加干扰线和噪点1。
// 添加干扰元素(线条和点)
for($i = 0; $i < 10; $i++) {
imageline($image, rand(0, $image_width), rand(0, $image_height),
rand(0, $image_width), rand(0, $image_height), $line_color);
imagesetpixel($image, rand(0, $image_width), rand(0, $image_height), $line_color);
}imageline()函数参数:
image: 图像资源x1: 起点x坐标y1: 起点y坐标x2: 终点x坐标y2: 终点y坐标color: 线条颜色
imagesetpixel()函数参数:
image: 图像资源x: x坐标y: y坐标color: 像素颜色
10. 输出图像
设置正确的HTTP头并输出图像1。
// 输出图片
header('Content-Type: image/png');
imagepng($image);
// 销毁图像资源
imagedestroy($image);imagepng()函数参数:
image: 图像资源file(可选): 文件路径,如果省略则直接输出到浏览器quality(可选): 压缩级别(0-9)filters(可选): PNG过滤器
三、高级改进方案
1. 使用TrueType字体
内置字体样式有限,可以使用TrueType字体增强效果5。
// 使用TrueType字体 $font = 'arial.ttf'; // 字体文件路径 $font_size = 20; $angle = rand(-5, 5); // 随机倾斜角度 imagettftext($image, $font_size, $angle, 20, 35, $text_color, $font, $captcha_text);
imagettftext()函数参数:
image: 图像资源size: 字体大小(像素)angle: 文本角度(0-360)x: 左下角x坐标y: 左下角y坐标color: 文本颜色fontfile: 字体文件路径text: 要写入的文本
2. 添加中文验证码
GD库也支持生成中文验证码5。
// 中文验证码示例
$str = "芸芸众生绿水青山名胜古迹敞开心胸便会云蒸霞蔚";
$zhongwenku = array();
for($i = 0; $i < mb_strlen($str, "UTF-8"); $i++) {
$zhongwenku[$i] = mb_substr($str, $i, 1, "UTF-8");
}
$captcha_text = '';
for($i = 0; $i < 4; $i++) {
$captcha_text .= $zhongwenku[rand(0, count($zhongwenku) - 1)];
}3. 添加扭曲效果
增加验证码的扭曲效果可以提高安全性6。
// 创建扭曲效果
$distorted_image = imagecreatetruecolor($image_width, $image_height);
imagefilledrectangle($distorted_image, 0, 0, $image_width, $image_height, $background_color);
// 扭曲处理
for($x = 0; $x < $image_width; $x++) {
for($y = 0; $y < $image_height; $y++) {
$new_x = $x + rand(-1, 1);
$new_y = $y + rand(-1, 1);
if($new_x >= 0 && $new_x < $image_width && $new_y >= 0 && $new_y < $image_height) {
$color = imagecolorat($image, $x, $y);
imagesetpixel($distorted_image, $new_x, $new_y, $color);
}
}
}五、验证码验证
生成验证码后,需要验证用户输入是否正确。
<?php
session_start();
if(isset($_POST['captcha'])) {
if(strtolower($_POST['captcha']) == strtolower($_SESSION['captcha'])) {
echo "验证码正确";
} else {
echo "验证码错误";
}
}
?>六、注意事项
会话安全: 确保在生成验证码前调用
session_start()字符集选择: 避免使用易混淆字符如0/O, 1/l等
图像尺寸: 根据验证码长度调整图像宽度
颜色对比: 确保文字颜色与背景色有足够对比度
资源释放: 使用
imagedestroy()释放图像资源字体路径: 使用TrueType字体时确保路径正确
性能考虑: 避免在循环中频繁创建图像资源
安全性: 验证码应有一定复杂度防止机器识别
七、常见问题解决
GD库未加载: 检查php.ini中是否启用了gd扩展
图像不显示: 确保输出图像前没有其他输出(包括空格)
字体不显示: 检查字体文件路径和权限
验证码不匹配: 检查会话是否正常工作
图像质量差: 尝试使用PNG格式而非JPEG
通过以上步骤,您可以完整地实现PHP中使用GD库生成验证码的功能,并根据需要调整样式和复杂度。