HTTP_X_FORWARDED_FOR, HTTP_CLIENT_IP)<?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);
?>
<?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);
?>
ip_signature.php 放入網站目錄。[img]https://yourdomain.com/ip_signature.php[/img]。<img src="https://yourdomain.com/ip_signature.php" alt="My IP">。header('Content-Length: ' . strlen($pngData)) (需先輸出到變數)。fastcgi_cache 快取 1-5 秒,或生成靜態圖片定時更新。動態生成 IP 簽名圖是 GD 庫入門絕佳練習,涵蓋 HTTP Header 處理、IP 偵測邏輯、圖片建立/繪文字/透明度/輸出。掌握此技術可延伸至:驗證碼生成、圖表繪製、水印添加、海報合成、API 狀態徽章等場景。