php实现图片验证码
实现图片验证码的步骤
生成随机字符串
使用rand()或mt_rand()函数生成随机数,再转换为字符。也可以定义包含数字和字母的字符串,随机选取字符组合成验证码。
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz23456789';
$code = substr(str_shuffle($chars), 0, 4);
创建图像资源
使用imagecreatetruecolor()函数创建指定宽高的图像资源。背景色可通过imagecolorallocate()设置。
$width = 100;
$height = 30;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
添加干扰元素
增加干扰线或干扰点提高安全性。使用imageline()画线或imagesetpixel()画点。

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);
}
绘制验证码文本
使用imagettftext()或imagestring()将验证码文本绘制到图像上。可设置字体、颜色和位置。
$font = 'path/to/font.ttf';
for ($i = 0; $i < strlen($code); $i++) {
$color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
imagettftext($image, 20, rand(-30, 30), 10 + $i * 20, 25, $color, $font, $code[$i]);
}
输出图像并销毁资源
设置响应头为图像类型,使用imagepng()输出图像,最后销毁资源释放内存。

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
存储验证码
将生成的验证码存入$_SESSION,便于后续验证。
session_start();
$_SESSION['captcha'] = $code;
完整示例代码
session_start();
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz23456789';
$code = substr(str_shuffle($chars), 0, 4);
$_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);
}
$font = 'arial.ttf';
for ($i = 0; $i < strlen($code); $i++) {
$color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
imagettftext($image, 20, rand(-30, 30), 10 + $i * 20, 25, $color, $font, $code[$i]);
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
验证用户输入
在表单提交时,比较用户输入与$_SESSION中的验证码是否一致。
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo '验证码正确';
} else {
echo '验证码错误';
}






