php实现图形验证码
生成随机验证码字符串
使用rand()或mt_rand()函数生成随机数字,或结合chr()函数生成随机字母。验证码长度通常为4-6位:
$length = 4;
$code = '';
$charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < $length; $i++) {
$code .= $charset[rand(0, strlen($charset) - 1)];
}
$_SESSION['captcha'] = $code; // 存储到SESSION
创建图像资源
使用GD库创建画布并设置背景:

$width = 100;
$height = 30;
$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(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 < 50; $i++) {
$color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
绘制验证码文本
将生成的验证码字符串绘制到图像上:

$textColor = imagecolorallocate($image, 0, 0, 0);
$font = 5; // 内置字体
imagestring($image, $font, 30, 8, $code, $textColor);
// 若使用TTF字体
// $fontFile = 'path/to/font.ttf';
// imagettftext($image, 20, 0, 10, 25, $textColor, $fontFile, $code);
输出图像
设置HTTP头并输出图像:
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
完整示例代码
session_start();
$length = 4;
$charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $charset[rand(0, strlen($charset) - 1)];
}
$_SESSION['captcha'] = $code;
$width = 100;
$height = 30;
$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(0, 255), rand(0, 255), rand(0, 255));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
}
$textColor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 30, 8, $code, $textColor);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
验证用户输入
在表单提交处理页面验证:
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo '验证码正确';
} else {
echo '验证码错误';
}
unset($_SESSION['captcha']); // 验证后销毁






