萬盛學電腦網

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

PHP 實作圖形驗證碼防惡意註冊完整教學

驗證碼核心原理

利用 GD 庫生成包含隨機字符的圖片,將字符存入 Session,用戶提交時比對。機器難以識別扭曲、干擾線、噪點的圖片,從而防止自動化腳本惡意註冊。

完整實現流程

1. 生成驗證碼圖片 captcha.php

<?php
session_start();

// 1. 生成 4 位隨機數字
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= random_int(0, 9); // 比 rand() 更安全
}
// 存入 Session
$_SESSION['captcha_code'] = $code;

// 2. 創建畫布
$width = 80; $height = 30;
$im = imagecreatetruecolor($width, $height); // 真彩色畫布

// 3. 分配顏色
$bg = imagecolorallocate($im, 220, 220, 220); // 淺灰背景
$textColor = imagecolorallocate($im, 0, 0, 0); // 黑色文字
$noiseColor = imagecolorallocate($im, 150, 150, 150); // 噪點顏色

// 4. 填充背景
imagefill($im, 0, 0, $bg);

// 5. 繪製干擾線 (隨機 3 條)
for ($i = 0; $i < 3; $i++) {
    imageline($im,
        random_int(0, $width), random_int(0, $height),
        random_int(0, $width), random_int(0, $height),
        $noiseColor
    );
}

// 6. 繪製干擾像素點 (隨機 50 個)
for ($i = 0; $i < 50; $i++) {
    imagesetpixel($im, random_int(0, $width), random_int(0, $height), $noiseColor);
}

// 7. 繪製驗證碼字符 (隨機位置、字體大小)
$fontSize = 5; // 內置字體 1-5
$x = 10;
for ($i = 0; $i < 4; $i++) {
    $y = random_int(2, 10);
    $char = $code[$i];
    imagestring($im, $fontSize, $x, $y, $char, $textColor);
    $x += random_int(15, 20); // 隨機間距
}

// 8. 輸出圖片並銷毀資源
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>

2. 註冊表單 register.php

<form method="post" action="verify.php">
    <div>
        <label>驗證碼:</label>
        <input type="text" name="captcha" required style="width:60px;">
        <img src="captcha.php" id="captchaImg" alt="點擊刷新" style="cursor:pointer; vertical-align:middle;" title="點擊刷新">
    </div>
    <button type="submit">註冊</button>
</form>

<script>
// 點擊圖片刷新驗證碼
document.getElementById('captchaImg').onclick = function() {
    this.src = 'captcha.php?' + Date.now(); // 防緩存
};
</script>

3. 驗證邏輯 verify.php

<?php
session_start();

function fail($msg) {
    exit("<script>alert('$msg'); history.back();</script>");
}

// 1. 檢查提交
if (empty($_POST['captcha'])) fail('請輸入驗證碼');

// 2. 比對 (不區分大小寫可用 strtolower)
if (strtolower($_POST['captcha']) !== strtolower($_SESSION['captcha_code'])) {
    fail('驗證碼錯誤');
}

// 3. 驗證通過,執行註冊邏輯...
echo '驗證通過,處理註冊...';
// 註冊業務代碼...
?>

安全加固建議

  • 使用 `random_int()` 替代 `rand()`:加密級隨機數,防止預測。
  • Session 防固定:登錄前後 `session_regenerate_id(true)`。
  • 圖片複雜度:增加字體扭曲 (需 FreeType + `imagettftext()`)、隨機旋轉、背景圖片、更多干擾線/點。
  • 限制嘗試次數:同一 IP/Session 限制驗證失敗次數,防暴力破解。
  • 無障礙備選:提供音頻驗證碼或簡單算術題 (如 "3+5=?")。
  • 現代替代方案:考慮 Google reCAPTCHA v3 / hCaptcha / Turnstile,體驗更好、安全性更高。

Session 銷毀最佳實踐 (登出)

<?php
session_start();
// 1. 清空 $_SESSION
$_SESSION = [];
// 2. 刪除 Session Cookie
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}
// 3. 銷毀 Session
session_destroy();
echo '已登出';
?>
copyright © 萬盛學電腦網 all rights reserved