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

PHP 簡易圖形驗證碼生成實作

     編輯:PHP 相關知識

GD 庫生成基礎驗證碼

利用 PHP GD 擴展繪製簡單數字驗證碼,儲存於 Session 供後續驗證。

完整程式碼

<?php
// 必須啟動 Session
if (!isset($_SESSION)) {
    session_start();
    header('Cache-control: private');
}

// 建立 65x20 像素畫布
$width = 65;
$height = 20;
$image = imagecreate($width, $height);

// 背景色
$bg_color = imagecolorallocate($image, 0x33, 0x66, 0xFF);
imagefilledrectangle($image, 0, 0, $width, $height, $bg_color);

// 產生 5 位隨機字串
$text = random_text(5); // 需自行實作 random_text()

// 計算文字置中座標
$font = 5;
$x = imagesx($image) / 2 - strlen($text) * imagefontwidth($font) / 2;
$y = imagesy($image) / 2 - imagefontheight($font) / 2;

// 繪製文字
$fg_color = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
imagestring($image, $font, $x, $y, $text, $fg_color);

// 存入 Session
$_SESSION['captcha'] = $text;

// 輸出圖片
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

驗證邏輯

<?php
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
    echo '驗證通過';
} else {
    echo '驗證碼錯誤';
}
?>

改進方向

  • 加入干擾線、噪點提高識別難度。
  • 使用 TTF 字體(imagettftext())實現傾斜、變形效果。
  • 考慮使用成熟套件如 gregwar/captcha。

簡易驗證碼適合低風險場景,高安全需求請採用成熟庫或第三方驗證服務(如 reCAPTCHA)。

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