Files
2026-08-14 10:55:06 +08:00

51 lines
1.6 KiB
PHP

<?php
// 自研图形验证码:输出 4 位字符图片,代码存入 session。
// 不依赖任何第三方库,纯 GD 绘制;无 GD 时降级为纯文本兜底。
session_start();
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // 去除 0/O/1/I 等易混字符
$len = 4;
$code = '';
for ($i = 0; $i < $len; $i++) {
$code .= $chars[random_int(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = $code;
if (!extension_loaded('gd')) {
// 无 GD 扩展时降级:直接输出字符(仅兜底,建议开启 GD)
header('Content-Type: text/plain; charset=UTF-8');
echo $code;
exit;
}
$w = 120; $h = 44;
$img = imagecreatetruecolor($w, $h);
$bg = imagecolorallocate($img, 248, 250, 252);
imagefill($img, 0, 0, $bg);
// 干扰线
for ($i = 0; $i < 6; $i++) {
$c = imagecolorallocate($img, rand(180, 230), rand(190, 235), rand(200, 245));
imageline($img, rand(0, $w), rand(0, $h), rand(0, $w), rand(0, $h), $c);
}
// 干扰点
for ($i = 0; $i < 40; $i++) {
$c = imagecolorallocate($img, rand(180, 230), rand(190, 235), rand(200, 245));
imagesetpixel($img, rand(0, $w), rand(0, $h), $c);
}
// 逐个绘制字符(随机大小/角度/颜色,轻微错位形成扭曲)
for ($i = 0; $i < $len; $i++) {
$c = imagecolorallocate($img, rand(20, 90), rand(70, 140), rand(170, 230));
$size = rand(20, 26);
$angle = rand(-20, 20);
$x = 14 + $i * 26;
$y = rand(30, 38);
imagestring($img, 5, $x, $y - 16, $code[$i], $c);
}
header('Content-Type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
imagepng($img);
imagedestroy($img);