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

PHP 以圖片方式輸出客戶端 IP 位址(GD 庫、透明背景、多代理支援)

     編輯:PHP 相關知識

應用場景

  • 論壇簽名檔、部落格側邊欄顯示訪客 IP。
  • API 端點以圖片回應 IP,繞過 CSP/JS 限制嵌入靜態頁面。
  • 監控頁面以 <img src="/ip-image.php"> 即時顯示。

完整實作

<?php
// ip-image.php
header('Content-Type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

// 1. 取得真實 IP(支援多層代理)
$ip = '';
$headers = [
    'HTTP_CLIENT_IP',
    'HTTP_X_FORWARDED_FOR',
    'HTTP_X_FORWARDED',
    'HTTP_X_CLUSTER_CLIENT_IP',
    'HTTP_FORWARDED_FOR',
    'HTTP_FORWARDED',
    'REMOTE_ADDR',
];
foreach ($headers as $h) {
    if (!empty($_SERVER[$h])) {
        $ipList = array_map('trim', explode(',', $_SERVER[$h]));
        $ip = $ipList[0]; // 取第一個(最原始客戶端)
        break;
    }
}
$ip = $ip ?: 'Unknown';

// 2. 建立畫布(寬度依 IP 長度動態調整)
$fontSize = 3; // 1-5 內建字體
$charWidth  = imagefontwidth($fontSize);
$charHeight = imagefontheight($fontSize);
$padding = 6;
$width  = $padding * 2 + strlen($ip) * $charWidth;
$height = $padding * 2 + $charHeight;

$im = imagecreatetruecolor($width, $height);

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

// 4. 文字顏色(深藍)
$textColor = imagecolorallocate($im, 0, 51, 102);

// 5. 繪製文字
imagestring($im, $fontSize, $padding, $padding, $ip, $textColor);

// 6. 輸出並釋放
imagepng($im);
imagedestroy($im);

進階功能擴充

需求實作方式
自訂字體(TTF)imagettftext($im, $size, 0, $x, $y, $color, $fontPath, $ip),需 FreeType 支援
顯示地理位置整合 MaxMind GeoIP2 資料庫:$city = $reader->city($ip)->city->name
加入時間戳imagestring($im, ..., $ip . ' ' . date('H:i:s'))
高對比度主題提供 ?theme=dark 切換文字/背景色
限制存取頻率Redis 計數器 INCR ip:image:{$ip} 配合 TTL

HTML 嵌入方式

<img src="ip-image.php" alt="Your IP" title="Your IP">
<!-- 支援查詢參數 -->
<img src="ip-image.php?theme=dark&font=2" alt="IP">

效能與安全考量

  • 記憶體:單次請求約 50-200 KB,極輕量。
  • 快取:已發送 no-cache 標頭,確保即時性。
  • 代理 IP 可信度:X-Forwarded-For 可偽造,**僅信任已知代理層**(如 Cloudflare、Nginx 反向代理)傳遞的標頭,生產環境請在 Web 伺服器層(Nginx real_ip_module)清洗後再傳給 PHP。
  • GD vs Imagick:GD 內建、輕量;Imagick 功能強、支援更多格式,視環境選擇。

結語

PHP GD 庫輕鬆實現「IP 圖片化」,適合嵌入靜態頁、簽名檔、監控面板。關鍵在於正確解析多層代理下的真實 IP、透明背景美觀呈現、適當快取控制。生產環境建議配合 Web 伺服器層 IP 清洗與頻率限制,確保資料可信與服務穩定。

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