php实现图片验证码
使用PHP生成图片验证码
PHP可以通过GD库生成图片验证码,以下是具体实现方法。
创建验证码图片
使用imagecreatetruecolor函数创建一个空白图片,并填充背景色:
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
生成随机验证码字符串
创建包含数字和字母的随机字符串:

$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = 6;
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
将验证码写入图片
使用imagestring或imagettftext函数将验证码文本写入图片:
$textColor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 30, 12, $code, $textColor);
// 使用TrueType字体(需指定字体文件路径)
// $font = 'arial.ttf';
// imagettftext($image, 20, 0, 10, 30, $textColor, $font, $code);
添加干扰元素
增加干扰线和干扰点提高安全性:

// 干扰线
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);
}
// 干扰点
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);
}
输出图片并保存验证码
输出图片到浏览器并将验证码存入session:
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
// 保存验证码到session
session_start();
$_SESSION['captcha'] = $code;
完整示例代码
<?php
session_start();
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = 6;
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
$textColor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 30, 12, $code, $textColor);
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);
}
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);
}
$_SESSION['captcha'] = $code;
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
验证码验证
在表单提交后验证用户输入:
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo "验证码正确";
} else {
echo "验证码错误";
}
注意事项
确保服务器已安装GD库扩展,可通过phpinfo()查看。TrueType字体需要指定字体文件路径。为提高安全性,可考虑使用更复杂的验证码生成算法或第三方验证码库。






