查看效果:PHP验证码

<?php
session_start();

// 修正:补回漏掉的字母 j
$glbVerifySeed = "1234567890abcdefghijklmnopqrstuvwxyz";

main();

function main()
{
    $verifyCode = getRandomCode();
    $_SESSION["verifyCode"] = $verifyCode;

    // 修正:先 isset 判断,再 intval 转换,避免 Notice 与非法类型
    $imgWidth  = isset($_REQUEST["width"])  ? intval($_REQUEST["width"])  : 0;
    $imgHeight = isset($_REQUEST["height"]) ? intval($_REQUEST["height"]) : 0;
    $imgFont   = isset($_REQUEST["font"])   ? intval($_REQUEST["font"])   : 0;

    // 修正:增加范围校验,防止超大图像导致内存耗尽
    if ($imgWidth  < 40 || $imgWidth  > 200) $imgWidth  = 80;
    if ($imgHeight < 15 || $imgHeight > 60)  $imgHeight = 18;
    if ($imgFont   < 1  || $imgFont   > 8)   $imgFont   = 6;

    doOutputImg($verifyCode, $imgWidth, $imgHeight, $imgFont);
}

function getRandomCode($length = 6)
{
    global $glbVerifySeed;

    $bgnIdx = 0;
    $endIdx = strlen($glbVerifySeed) - 1;

    $code = "";
    for ($i = 0; $i < $length; $i++) {
        $curPos = random_int($bgnIdx, $endIdx); // 修正:使用安全随机数
        $code  .= substr($glbVerifySeed, $curPos, 1);
    }

    return $code;
}

function doOutputImg($string, $imgWidth, $imgHeight, $imgFont,
                     $imgFgColorArr = array(0, 0, 0),
                     $imgBgColorArr = array(255, 255, 255))
{
    $image = imagecreatetruecolor($imgWidth, $imgHeight);

    // 修正:背景色改用传入参数,不再写死
    $backColor   = imagecolorallocate($image, $imgBgColorArr[0], $imgBgColorArr[1], $imgBgColorArr[2]);
    $borderColor = imagecolorallocate($image, 0, 0, 0);

    imagefilledrectangle($image, 0, 0, $imgWidth - 1, $imgHeight - 1, $backColor);
    imagerectangle($image, 0, 0, $imgWidth - 1, $imgHeight - 1, $borderColor);

    $imgFgColor = imagecolorallocate($image, $imgFgColorArr[0], $imgFgColorArr[1], $imgFgColorArr[2]);
    doDrawStr($image, $string, $imgFgColor, $imgFont);
    doPollute($image, 64);

    header('Content-type: image/png');
    imagepng($image);
    imagedestroy($image);
}

function doDrawStr($image, $string, $color, $imgFont)
{
    $imgWidth  = imagesx($image);
    $imgHeight = imagesy($image);

    $count = strlen($string);
    $xpace = ($imgWidth / $count);

    $x = ($xpace - 6) / 2;
    $y = ($imgHeight / 2 - 8);

    for ($p = 0; $p < $count; $p++) {
        $xoff = mt_rand(-2, +2);
        $yoff = mt_rand(-2, +2);
        $curChar = substr($string, $p, 1);
        imagestring($image, $imgFont, $x + $xoff, $y + $yoff, $curChar, $color);
        $x += $xpace;
    }
}

function doPollute($image, $times)
{
    $imgWidth  = imagesx($image);
    $imgHeight = imagesy($image);

    for ($j = 0; $j < $times; $j++) {
        // 修正:坐标上限改为 width-1 / height-1,避免越界
        $x = mt_rand(0, $imgWidth - 1);
        $y = mt_rand(0, $imgHeight - 1);
        $color = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
        imagesetpixel($image, $x, $y, $color);
    }
}