首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP GD 繪製驗證碼完整函數實例

     編輯:PHP 綜合知識

功能特性

  • 可自訂長度、寬高。
  • 隨機十六進位字元 (0-9, a-f)。
  • 背景噪點、干擾線、邊框。
  • 儲存至 $_SESSION['code'] 供驗證。
  • 直接輸出 PNG 圖片流。

完整函數程式碼

<?php
function generateCaptcha($length = 4, $width = 100, $height = 30) {
    // 1. 產生隨機碼
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= dechex(mt_rand(0, 15)); // 0-9 a-f
    }
    $_SESSION['captcha_code'] = $code;

    // 2. 建立畫布
    $img = imagecreatetruecolor($width, $height);
    $white = imagecolorallocate($img, 250, 250, 250);
    imagefill($img, 0, 0, $white);

    // 3. 邊框
    $gray = imagecolorallocate($img, 196, 196, 196);
    imagerectangle($img, 0, 0, $width - 1, $height - 1, $gray);

    // 4. 干擾線 (6 條)
    for ($i = 0; $i < 6; $i++) {
        $color = imagecolorallocate($img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
        imageline($img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $color);
    }

    // 5. 噪點 (50 個 *)
    for ($i = 0; $i < 50; $i++) {
        $color = imagecolorallocate($img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
        imagestring($img, 1, mt_rand(1, $width - 5), mt_rand(1, $height - 5), '*', $color);
    }

    // 6. 繪製驗證碼字元
    for ($i = 0; $i < $length; $i++) {
        $color = imagecolorallocate($img, mt_rand(0, 102), mt_rand(0, 102), mt_rand(0, 102));
        $x = $i * $width / $length + mt_rand(1, 10);
        $y = mt_rand(1, $height / 2);
        imagestring($img, 5, $x, $y, $code[$i], $color);
    }

    // 7. 輸出
    header('Content-Type: image/png');
    imagepng($img);
    imagedestroy($img);
}

// 使用範例
session_start();
generateCaptcha(4, 120, 40);

前端整合範例

<img src="captcha.php" id="captchaImg" style="cursor:pointer" title="點擊刷新">
<input type="text" name="captcha" placeholder="輸入驗證碼">

<script>
document.getElementById('captchaImg').onclick = function() {
    this.src = 'captcha.php?' + Date.now(); // 防快取
};
</script>

後端驗證

session_start();
if (strtolower($_POST['captcha']) !== strtolower($_SESSION['captcha_code'])) {
    die('驗證碼錯誤');
}
// 通過,執行業務邏輯...

進階建議

  • 字元集擴充:混合大小寫字母、數字、排除易混淆字元 (0/O, 1/l)。
  • 使用 TTF 字體 imagettftext() 取代 imagestring(),效果更佳。
  • 加入 Session 過期時間(如 10 分鐘),防止重放攻擊。
  • 高併發場景考慮將驗證碼存入 Redis,減少 Session 檔案 I/O。

總結

此函數提供開箱即用的 GD 驗證碼生成,涵蓋畫布建立、噪點干擾、字元繪製、Session 存儲、PNG 輸出全流程。可直接放入 captcha.php 供前端呼叫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved