萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 依 IP 取得地理位置(省市)並實現城市導向跳轉

呼叫新浪 IP 定位介面

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'] ?? '';
}

前端 JS 依城市導向跳轉

<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>

現代替代方案

  • 使用 MaxMind GeoIP2 離線資料庫(composer require geoip2/geoip2),無外部依賴、回應極快。
  • 雲端服務:ipapi.co、ipinfo.io、cloudflare.com/cdn-cgi/trace(需付費/限流)。
  • Nginx ngx_http_geoip2_module 直接在伺服器層導向。

隱私合規提醒

收集 IP 屬個人資料,須符合 GDPR、個資法等法規,公開隱私權政策、提供選擇退出機制。

copyright © 萬盛學電腦網 all rights reserved