function GetIpLookup($ip = '') {
if (empty($ip)) return '請輸入 IP 位址';
$url = "https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip={$ip}";
$res = @file_get_contents($url);
if (empty($res)) return false;
// 回傳格式:var remote_ip_info = {...};
preg_match('#\{.+?\}#', $res, $matches);
if (!isset($matches[0])) return false;
$json = json_decode($matches[0], true);
if (isset($json['ret']) && $json['ret'] == 1) {
$json['ip'] = $ip;
unset($json['ret']);
return $json;
}
return false;
}
// 使用範例
$ipInfo = GetIpLookup('123.125.114.144'); // baidu.com IP
var_dump($ipInfo);
/* 輸出範例:
array(
'country' => '中国',
'province' => '北京',
'city' => '北京',
'district' => '',
'isp' => '电信',
'type' => '',
'ip' => '123.125.114.144'
)
*/
function getIpCity() {
$content = file_get_contents("https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js");
$json = json_decode(substr(strstr($content, '='), 1), true);
return $json['city'] ?? '';
}
<script>
// PHP 端輸出城市變數給 JS
var city = '<?php echo getIpCity(); ?>';
if (city.indexOf('上海市') >= 0) {
window.location.href = 'https://shanghai.example.com/';
} else if (city.indexOf('北京市') >= 0) {
window.location.href = 'https://beijing.example.com/';
}
// 更多城市...
</script>
composer require geoip2/geoip2),無外部依賴、回應極快。ipapi.co、ipinfo.io、cloudflare.com/cdn-cgi/trace(需付費/限流)。ngx_http_geoip2_module 直接在伺服器層導向。收集 IP 屬個人資料,須符合 GDPR、個資法等法規,公開隱私權政策、提供選擇退出機制。