图形验证码:生成与校验
用 GD 生成四位验证码,带干扰线和噪点,答案存会话,校验后立即失效,防止被脚本刷。
更新于 2026-11-1647 行代码
PHP
<?php
function captcha_image(string $code, int $w = 120, int $h = 40): void
{
$im = imagecreatetruecolor($w, $h);
$bg = imagecolorallocate($im, 246, 247, 251);
imagefilledrectangle($im, 0, 0, $w, $h, $bg);
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
for ($i = 0; $i < 4; $i++) {
$c = imagecolorallocate($im, random_int(40, 110), random_int(40, 110), random_int(120, 190));
imagestring($im, 5, 14 + $i * 24, random_int(8, 18), $code[$i], $c);
}
for ($i = 0; $i < 4; $i++) {
$c = imagecolorallocate($im, random_int(150, 210), random_int(150, 210), random_int(150, 210));
imageline($im, 0, random_int(0, $h), $w, random_int(0, $h), $c);
}
for ($i = 0; $i < 120; $i++) {
$c = imagecolorallocate($im, random_int(180, 230), random_int(180, 230), random_int(180, 230));
imagesetpixel($im, random_int(0, $w), random_int(0, $h), $c);
}
header('Content-Type: image/png');
header('Cache-Control: no-store');
imagepng($im);
imagedestroy($im);
}
function captcha_new(): string
{
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[random_int(0, strlen($chars) - 1)];
}
$_SESSION['captcha'] = strtoupper($code);
$_SESSION['captcha_at'] = time();
return $code;
}
function captcha_check(string $input): bool
{
$ok = isset($_SESSION['captcha'], $_SESSION['captcha_at'])
&& time() - $_SESSION['captcha_at'] < 300
&& strtoupper(trim($input)) === $_SESSION['captcha'];
unset($_SESSION['captcha'], $_SESSION['captcha_at']);
return $ok;
}