萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP GD 庫生成變色驗證碼:指定顏色字符輸入驗證

效果描述

驗證碼圖片中字符顏色不一致,要求用戶**只輸入指定顏色(如紅色)的字符**,大幅提高機器識別難度。

完整實現代碼

<?php
header("Content-type: image/png; charset=utf-8");

// 1. 創建畫布
$width = 400; $height = 30;
$im = imagecreatetruecolor($width, $height);

// 2. 分配顏色
$white  = imagecolorallocate($im, 255, 255, 255);
$red    = imagecolorallocate($im, 255, 0, 0);
$black  = imagecolorallocate($im, 0, 0, 0);
$green  = imagecolorallocate($im, 0, 255, 0);
$blue   = imagecolorallocate($im, 0, 0, 255);
$color_arr = array($green, $blue, $red); // 變色池
$color = array_rand($color_arr); // 隨機選一種變色

// 3. 驗證碼文本(中文)
$text = '我靠這驗證碼太變態啦';
$textlen = mb_strlen($text, 'utf-8'); // 多字節長度

// 4. 隨機選取兩個位置作為變色字符
$p1 = rand(0, $textlen - 1);
do { $p2 = rand(0, $textlen - 1); } while ($p2 == $p1);
$w1 = mb_substr($text, $p1, 1, 'utf-8');
$w2 = mb_substr($text, $p2, 1, 'utf-8');

// 5. 字體文件(需確保 simkai.ttf 存在於項目目錄)
$font = 'simkai.ttf';

// 6. 填充白色背景
imagefilledrectangle($im, 0, 0, $width-1, $height-1, $white);

// 7. 逐字符繪製
for ($i = 0; $i < $textlen; $i++) {
    $char = mb_substr($text, $i, 1, 'utf-8');
    $x = 20 * $i + 10; // 簡單等寬佈局
    $y = 20;

    if ($i == $p1 || $i == $p2) {
        // 變色字符
        imagettftext($im, 15, 0, $x, $y, $color_arr[$color], $font, $char);
    } else {
        // 普通黑色字符
        imagettftext($im, 15, 0, $x, $y, $black, $font, $char);
    }
}

// 8. 可選:添加干擾線/點
for ($i=0; $i<5; $i++) {
    imageline($im, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $color_arr[array_rand($color_arr)]);
}
for ($i=0; $i<50; $i++) {
    imagesetpixel($im, rand(0,$width), rand(0,$height), $color_arr[array_rand($color_arr)]);
}

// 9. 輸出並銷毀
imagepng($im);
imagedestroy($im);

// 10. 將驗證信息存入 Session 供驗證
session_start();
$_SESSION['captcha_chars'] = [$w1, $w2]; // 存儲兩個變色字符
$_SESSION['captcha_color'] = $color_arr[$color]; // 存儲變色顏色資源ID(或顏色名)
?>

前端驗證邏輯

<form action="verify.php" method="post">
    <img src="captcha.php" id="captcha" onclick="this.src='captcha.php?'+Math.random()" /><br/>
    請輸入 紅色 字符:<input name="captcha_input" />
    <button type="submit">提交</button>
</form>

// verify.php
session_start();
$input = $_POST['captcha_input'] ?? '';
$expected = implode('', $_SESSION['captcha_chars'] ?? []);
if (strtolower($input) === strtolower($expected)) {
    echo "驗證通過";
} else {
    echo "驗證失敗,請輸入紅色字符";
}

優化建議

  1. 字體文件:確保 `simkai.ttf` 可讀,或使用 `imageloadfont` 載入 `.gdf` 字體。
  2. Session 存儲:生產環境用 Redis 存儲驗證碼,設置 5-10 分鐘過期。
  3. 干擾強度:隨機字體大小、旋轉角度、字符間距、干擾線條/噪點密度。
  4. 無障礙:提供音頻驗證碼選項。
  5. 現代替代**:考慮 Google reCAPTCHA v3 / hCaptcha / Geetest 等行為驗證,體驗更好、安全性更高。
copyright © 萬盛學電腦網 all rights reserved