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

PHP GD 實作精美圖形驗證碼:星星干擾、隨機傾斜與 TTF 字型支援

     編輯:PHP 相關知識

打造視覺優雅且機器難識別的驗證碼:使用 TrueType 字型渲染字元、隨機旋轉角度、星星狀干擾點與波浪干擾線,支援不區分大小寫驗證,字型檔需置於 Web 目錄。

完整實作代碼

<?php
/* @Author fy */
$imgwidth  = 100;
$imgheight = 40;
$codelen   = 4;
$fontsize  = 20;
$charset   = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';  // 排除易混淆字元
$font      = 'Fonts/segoesc.ttf';  // Win7 內建字型,需上傳至專案

$im = imagecreatetruecolor($imgwidth, $imgheight);
$white = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $white);

// 生成隨機驗證碼
$authstr = '';
$_len = strlen($charset) - 1;
for ($i = 0; $i < $codelen; $i++) {
    $authstr .= $charset[mt_rand(0, $_len)];
}

session_start();
$_SESSION['scode'] = strtolower($authstr);  // 統一小寫,不區分大小寫

// 繪製星星干擾點
for ($i = 0; $i < $imgwidth; $i++) {
    $randcolor = imagecolorallocate($im, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
    imagestring($im, mt_rand(1, 5), mt_rand(0, $imgwidth), mt_rand(0, $imgheight), '*', $randcolor);
}

// 繪製水平干擾線
for ($i = 0; $i < $codelen; $i++) {
    $randcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
    imageline($im, 0, mt_rand(0, $imgheight), $imgwidth, mt_rand(0, $imgheight), $randcolor);
}

// 繪製驗證碼字元(隨機水平位移、垂直置中、隨機旋轉 -30~30 度)
$_x = intval($imgwidth / $codelen);
$_y = intval($imgheight * 0.7);
for ($i = 0; $i < strlen($authstr); $i++) {
    $randcolor = imagecolorallocate($im, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
    imagettftext($im, $fontsize, mt_rand(-30, 30), $i * $_x + 3, $_y, $randcolor, $font, $authstr[$i]);
}

// 輸出圖片
header("content-type:image/PNG");
imagepng($im);
imagedestroy($im);
?>

關鍵技術亮點

  • 字元集優化:移除 0/O、1/I/l、8/B 等易混淆字元
  • TTF 字型渲染:imagettftext() 支援反鋸齒、旋轉、精確定位
  • 視覺干擾層次:淡色星星點 + 彩色波浪線 + 深色字元,人眼易讀、OCR 難辨
  • Session 安全儲存:統一轉小寫儲存,驗證時同樣轉小寫比對

部署注意事項

  1. 確認伺服器已編譯 --with-freetype-dir 支援 TTF
  2. 字型檔 segoesc.ttf 需放置於可讀路徑(建議專案內 Fonts/ 目錄)
  3. 若出現空白圖片,多為字型路徑錯誤或 GD 未支援 FreeType
  4. 高併發場景建議改用 imagepng($im, null, 9) 壓縮等級 9 減少頻寬
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved