<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 |
<img src="ip-image.php" alt="Your IP" title="Your IP">
<!-- 支援查詢參數 -->
<img src="ip-image.php?theme=dark&font=2" alt="IP">
no-cache 標頭,確保即時性。X-Forwarded-For 可偽造,**僅信任已知代理層**(如 Cloudflare、Nginx 反向代理)傳遞的標頭,生產環境請在 Web 伺服器層(Nginx real_ip_module)清洗後再傳給 PHP。PHP GD 庫輕鬆實現「IP 圖片化」,適合嵌入靜態頁、簽名檔、監控面板。關鍵在於正確解析多層代理下的真實 IP、透明背景美觀呈現、適當快取控制。生產環境建議配合 Web 伺服器層 IP 清洗與頻率限制,確保資料可信與服務穩定。