写给愿意动手的 PHP 开发者
PHP学习网 PHP学习网
公告PHP学习网为公益性网站,致力于为广大PHP爱好者服务
首页/ PHP 源码/ 图形验证码:生成与校验
安全相关 通用 PHP 7.4 + GD

图形验证码:生成与校验

用 GD 生成四位验证码,带干扰线和噪点,答案存会话,校验后立即失效,防止被脚本刷。

完整代码

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;
}

怎么用

  1. 验证码图片单独一个入口:session_start(); $code = captcha_new(); captcha_image($code);
  2. 表单里放 <img src="/captcha.php?t=时间戳">,点击时换时间戳刷新。
  3. 提交后调用 captcha_check($_POST['code']),无论对错都立即销毁。

注意

  • 必须 unset,验证码不能重复使用,否则可以被暴力枚举。
  • 验证码接口要加 no-store,否则浏览器或 CDN 缓存会导致验证码永远不变。
  • imagestring 用的是内置字体,想更好看得用 imagettftext 加字体文件。

相关源码