代理、CDN、負載均衡環境下,$_SERVER['REMOTE_ADDR'] 往往是代理 IP。需按優先級檢查多個頭部:
<?php
/**
* 獲取客戶端真實 IP
* @return string IPv4 地址或 'unknown'
*/
function getClientIp(): string {
$ipKeys = [
'HTTP_CLIENT_IP', // 標準代理頭
'HTTP_X_FORWARDED_FOR', // 標準代理鏈(可能包含多個 IP,取第一個)
'HTTP_X_REAL_IP', // Nginx proxy_set_header 設置
'REMOTE_ADDR', // 直接連接或最後一級代理
];
foreach ($ipKeys as $key) {
if (!empty($_SERVER[$key])) {
// HTTP_X_FORWARDED_FOR 可能包含 "client, proxy1, proxy2",取首個
$ips = explode(',', $_SERVER[$key]);
$ip = trim($ips[0]);
// 簡單合法性校驗
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
// 允許私有/保留地址(內網測試環境)
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return $ip;
}
}
}
return 'unknown';
}
<?php
/**
* 調用新浪 IP 地址庫
* @param string $ip
* @return array|false ['country','province','city','isp',...] 或 false
*/
function getLocationSina(string $ip) {
$url = "https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={$ip}";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP IP Lookup)',
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
curl_close($ch);
if ($errno) {
error_log("Sina IP API curl error [{$errno}]: " . curl_error($ch));
return false;
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Sina IP API JSON decode error: " . json_last_error_msg());
return false;
}
// 新浪返回 ret=-1 表示失敗
if (isset($data['ret']) && $data['ret'] == -1) {
return false;
}
return $data; // 包含 country, province, city, district, isp, type 等
}
<?php
function getLocationIp138(string $ip): ?string {
$url = "https://www.ip138.com/ips138.asp?ip={$ip}";
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_USERAGENT => 'Mozilla/5.0',
]);
$html = curl_exec($ch);
curl_close($ch);
if (!$html) return null;
// 解析特定 HTML 結構(易失效,需維護)
if (preg_match('/- (.*?)<\/li>/is', $html, $m)) {
if (preg_match('/本站主數據:(.*)/i', $m[1], $m2)) {
return trim($m2[1]);
}
}
return null;
}
下載 qqwry.dat,使用成熟解析類(如 IPLocation):
<?php
require_once 'IPLocation.php'; // 需自行引入成熟解析類
$ipLoc = new IPLocation('/path/to/qqwry.dat');
$loc = $ipLoc->getlocation(getClientIp()); // 返回 ['country'=>..., 'area'=>...]
print_r($loc);
?>
<?php
require_once 'pinyin.php'; // 需引入拼音庫(如 overtrue/pinyin)
$pin = new \Overtrue\Pinyin\Pinyin();
$city = $loc['city'] ?? 'unknown';
$pinyin = $pin->permalink($city); // 獲取拼音 slug,如 beijing, shanghai
// 多音字/易錯城市人工修正表
$fixMap = [
'zhongqing' => 'chongqing', // 重慶
'shenfang' => 'shifang', // 什邡
'chengdou' => 'chengdu', // 成都
'yueshan' => 'leshan', // 樂山
'junxian' => 'xunxian', // 濬縣
'shamen' => 'xiamen', // 廈門
'zhangsha' => 'changsha', // 長沙
'weili' => 'yuli', // 尉犁
'zhaoyang' => 'chaoyang', // 朝陽
'danxian' => 'shanxian', // 單縣/鄯善
];
$cityEn = $fixMap[$pinyin] ?? $pinyin;
// 最終跳轉
header("Location: https://www.example.com/city/{$cityEn}");
exit;
<?php
// index.php
$ip = getClientIp();
if ($ip === 'unknown') {
die('無法獲取有效 IP');
}
$loc = getLocationSina($ip);
if (!$loc) {
// 降級嘗試 ip138 或本地庫
$loc = ['city' => 'beijing']; // 默認回落
}
$cityEn = $fixMap[$pin->permalink($loc['city'])] ?? $pin->permalink($loc['city']);
header("Location: https://www.example.com/{$cityEn}");
exit;
?>
IP 歸屬地解析鏈路:獲取真實 IP → 多源 API 調用與降級 → 城市標準化(拼音+多音字修正) → 業務跳轉/個性化。新浪接口免費穩定適合中小項目;大流量、高可用、隱私敏感場景請採用**本地 IP 庫(如 ip2region、MaxMind GeoIP2)**或商業服務(阿雲 IP 庫、騰訊位置服務)。