萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 動態生成 IP 簽名檔圖片:GD 庫繪製、代理 IP 偵測、透明背景優化

核心功能

  • 偵測真實客戶端 IP (支援代理 HTTP_X_FORWARDED_FOR, HTTP_CLIENT_IP)
  • 使用 GD 庫動態繪製 PNG 圖片
  • 可作為論壇簽名檔、部落格小工具、API 狀態徽章

完整實作代碼 (現代化重寫)

<?php
// ip_signature.php
header('Content-Type: image/png');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

// 1. 取得客戶端真實 IP
function getClientIp(): array
{
    $ipKeys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];
    $ips = [];
    foreach ($ipKeys as $key) {
        if (!empty($_SERVER[$key])) {
            // X-Forwarded-For 可能包含多個 IP (client, proxy1, proxy2...)
            $list = array_map('trim', explode(',', $_SERVER[$key]));
            $ips = array_merge($ips, $list);
        }
    }
    // 過濾私有/保留 IP,取第一個公網 IP
    foreach ($ips as $ip) {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
            return ['real' => $ip, 'proxy' => $_SERVER['REMOTE_ADDR']];
        }
    }
    // 全為私有 IP,返回 REMOTE_ADDR
    return ['real' => $_SERVER['REMOTE_ADDR'], 'proxy' => ''];
}

$ipInfo = getClientIp();
$realIp = $ipInfo['real'];
$proxyIp = $ipInfo['proxy'];

// 2. 繪圖參數
$fontSize = 2; // GD 內建字體 1-5
$padding = 10;
$lineHeight = imagefontheight($fontSize) + 4;
$textLines = [];

$textLines[] = "Your IP: $realIp";
if ($proxyIp) {
    $textLines[] = "Via Proxy: $proxyIp";
}
$textLines[] = "Time: " . date('Y-m-d H:i:s');
$textLines[] = "UA: " . substr($_SERVER['HTTP_USER_AGENT'] ?? 'Unknown', 0, 40);

// 3. 計算圖片尺寸
$maxWidth = 0;
foreach ($textLines as $line) {
    $w = imagefontwidth($fontSize) * strlen($line);
    if ($w > $maxWidth) $maxWidth = $w;
}
$imgWidth = $maxWidth + $padding * 2;
$imgHeight = count($textLines) * $lineHeight + $padding * 2;

// 4. 建立真彩色圖片 (支援透明度)
$im = imagecreatetruecolor($imgWidth, $imgHeight);

// 透明背景
imagesavealpha($im, true);
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $transparent);

// 顏色分配
$textColor = imagecolorallocate($im, 30, 30, 30);       // 深灰文字
$borderColor = imagecolorallocate($im, 180, 180, 180);  // 邊框

// 5. 繪製邊框 (圓角模擬)
imagerectangle($im, 0, 0, $imgWidth - 1, $imgHeight - 1, $borderColor);

// 6. 寫入文字
$y = $padding;
foreach ($textLines as $line) {
    imagestring($im, $fontSize, $padding, $y, $line, $textColor);
    $y += $lineHeight;
}

// 7. 輸出並銷毀
imagepng($im);
imagedestroy($im);
?>

進階:使用 TTF 字體 (支援中文、自訂字體)

<?php
// 需確認 GD 支援 FreeType: php -i | grep -i freetype
$fontFile = __DIR__ . '/fonts/NotoSansTC-Regular.otf'; // 自備字體檔
$fontSize = 14;
$color = [30, 30, 30];

// 計算文字邊界
$box = imagettfbbox($fontSize, 0, $fontFile, $realIp);
$textWidth = $box[2] - $box[0];
$textHeight = $box[1] - $box[7];

// ... 類似計算畫布大小 ...
// imagettftext($im, $fontSize, 0, $x, $y, $textColor, $fontFile, $text);
?>

部署方式

  1. 將 ip_signature.php 放入網站目錄。
  2. 論壇/部落格簽名檔設定:[img]https://yourdomain.com/ip_signature.php[/img]。
  3. 或 HTML:<img src="https://yourdomain.com/ip_signature.php" alt="My IP">。

效能優化

  • 啟用 OPcache (PHP 內建)。
  • 圖片輸出可加 header('Content-Length: ' . strlen($pngData)) (需先輸出到變數)。
  • 高流量考慮:Nginx fastcgi_cache 快取 1-5 秒,或生成靜態圖片定時更新。

結語

動態生成 IP 簽名圖是 GD 庫入門絕佳練習,涵蓋 HTTP Header 處理、IP 偵測邏輯、圖片建立/繪文字/透明度/輸出。掌握此技術可延伸至:驗證碼生成、圖表繪製、水印添加、海報合成、API 狀態徽章等場景。

copyright © 萬盛學電腦網 all rights reserved