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

PHP 簡易圖形驗證碼產生與驗證完整範例

     編輯:PHP 相關知識

PHP 簡易圖形驗證碼產生與驗證完整範例

圖形驗證碼是表單防機器人提交的基本防護。本文提供一組完整的驗證碼產生器(captcha.php)與驗證表單範例,使用 GD 函式庫繪製干擾線與隨機字元。

1. 驗證碼產生器 captcha.php

<?php
session_start();

// 設定驗證碼參數
$width = 100;
$height = 30;
$code_length = 4;
$font_size = 5;

// 產生隨機字元(0-9, a-f 十六進位)
$code = '';
for ($i = 0; $i < $code_length; $i++) {
    $code .= dechex(rand(1, 15));
}
$_SESSION['captcha_code'] = $code;

// 建立圖片畫布
$im = imagecreatetruecolor($width, $height);
$bg_color = imagecolorallocate($im, 0, 0, 0);       // 黑色背景
$text_color = imagecolorallocate($im, 255, 255, 255); // 白色文字

// 填滿背景
imagefilledrectangle($im, 0, 0, $width, $height, $bg_color);

// 繪製干擾線(可選)
for ($i = 0; $i < 5; $i++) {
    $line_color = imagecolorallocate($im, rand(100, 200), rand(100, 200), rand(100, 200));
    imageline($im, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $line_color);
}

// 繪製驗證碼文字
$x = 15;
$y = 20;
imagestring($im, $font_size, $x, $y, $code, $text_color);

// 輸出圖片
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
?>

2. 驗證表單與處理邏輯

<?php
session_start();

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['captcha_input']) && $_POST['captcha_input'] !== '') {
        if (strtolower($_POST['captcha_input']) === strtolower($_SESSION['captcha_code'] ?? '')) {
            $message = '<div style="color:green">驗證碼正確!</div>';
            // 這裡處理表單業務邏輯
        } else {
            $message = '<div style="color:red">驗證碼錯誤,請重新輸入。</div>';
        }
    } else {
        $message = '<div style="color:red">請輸入驗證碼。</div>';
    }
}
?>
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>驗證碼測試</title></head>
<body>
    <h2>驗證碼測試表單</h2>
    
    <form method="post">
        <img src="captcha.php" alt="驗證碼" style="vertical-align:middle; cursor:pointer" onclick="this.src='captcha.php?'+Date.now()" title="點擊更換">
        <br><br>
        <input type="text" name="captcha_input" placeholder="輸入驗證碼" required>
        <button type="submit">提交</button>
    </form>
</body>
</html>

關鍵點說明

  • Session 儲存:驗證碼儲存在 $_SESSION['captcha_code'],驗證時比對並忽略大小寫。
  • 點擊更換:onclick="this.src='captcha.php?'+Date.now()" 讓使用者無需重新整理頁面即可換碼。
  • 干擾線:簡單的隨機線條增加 OCR 辨識難度,正式專案建議使用更強健的字型扭曲、噪點等。
  • 安全性補充:實際部署請加入 header('Cache-Control: no-store, no-cache, must-revalidate'); 防止快取,並考慮使用 imagettftext() 載入 TTF 字型提升可讀性與安全性。

進階建議

現代專案建議使用成熟套件如 Gregwar/Captcha 或 mews/captcha(Laravel),支援更多樣化的驗證碼樣式、算術題、中文驗證碼等,且經過社群安全性驗證。

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