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

PHP 驗證碼(CAPTCHA)完整實作教學:產生、顯示與驗證流程

     編輯:PHP 相關知識

前言

驗證碼是防止機器人惡意提交表單的關鍵機制。本文完整示範 PHP 驗證碼的三階段實作:前端顯示頁面、後端圖片產生、驗證邏輯處理,並說明 Session 同步與 GD 函式庫需求。

第一階段:前端顯示與提交頁面 index.php

頁面包含:驗證碼圖片(透過 <iframe> 或 <img> 載入)、重新整理按鈕、輸入框與提交表單。

<?php
session_start();
header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>PHP 驗證碼示例</title>
</head>
<body>
    <p>驗證碼:<br>
    <iframe id="iimg" src="img.php" width="300" height="100" frameborder="0"></iframe><br>
    <input type="button" value="看不清,換一張" onclick="iimg.location.reload();"><br>
    <form action="validate.php" method="post">
        輸入驗證碼:<input name="imgId" style="width:60px">
        <input type="submit" value="確定">
    </form>
</body>
</html>

第二階段:驗證碼圖片產生 img.php

核心步驟:啟動 Session、產生隨機字串、寫入 Session、使用 GD 繪製干擾線與文字、輸出 GIF 圖片、銷毀圖片資源。

<?php
session_start();
header('Content-Type: image/gif');

// 產生 6 位隨機字元(大寫字母+數字)
$randval = '';
for ($i = 0; $i < 6; $i++) {
    $type = mt_rand(0, 1);
    $randval .= ($type === 0) ? chr(mt_rand(ord('A'), ord('Z'))) : mt_rand(0, 9);
}

// 存入 Session(注意:session_register 已棄用,直接賦值 $_SESSION)
$_SESSION['captcha_code'] = $randval;

// 建立真彩色圖片
$width = 120; $height = 40;
$im = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($im, 255, 255, 255);
$blue  = imagecolorallocate($im, 0, 0, 128);
imagefill($im, 0, 0, $white);

// 繪製干擾線
for ($k = 0; $k < 5; $k++) {
    imageline($im, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $blue);
}

// 繪製驗證碼文字
imagestring($im, 5, mt_rand(5, $width - 60), mt_rand(5, $height - 20), $randval, $blue);

imagegif($im);
imagedestroy($im);
?>

注意:需啟用 PHP GD 擴充套件(extension=gd),且儲存檔案為無 BOM UTF-8 編碼。

第三階段:驗證邏輯 validate.php

取得使用者輸入、轉大寫、與 Session 比對、銷毀 Session 防重複使用。

<?php
session_start();
header('Content-Type: text/html; charset=UTF-8');

$input = isset($_POST['imgId']) ? strtoupper(trim($_POST['imgId'])) : '';
$code  = isset($_SESSION['captcha_code']) ? $_SESSION['captcha_code'] : '';

if ($input !== '' && $input === $code) {
    echo '<font color="blue">通過驗證!</font>';
} else {
    echo '<font color="red">驗證錯誤!</font>';
}

// 驗證後銷毀,防止重放攻擊
session_destroy();
?>

進階改良建議

  • 使用 TTF 字型:imagettftext() 產生更難辨識的扭曲文字。
  • 加入噪點與干擾圓:imagesetpixel()、imageellipse() 提高機器辨識難度。
  • Session 命名空間:避免多組驗證碼衝突,如 $_SESSION['captcha']['login']。
  • 考慮現成方案:Gregwar/Captcha、mews/captcha 等 Composer 套件功能更完善。

總結

透過 Session 同步隨機字串與 GD 繪圖,即可快速建立可用的驗證碼機制。實務專案建議採用成熟套件並結合前端 AJAX 驗證,提升使用者體驗與安全性。

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