/ 網站開發

2023年11月18日 29

IP Geolocation API 用IP取得所在地的相關資訊


透過 IP Address 取得用戶的當前國別&城市的相關訊息
以前寫的落落長,效果也不是很好
最近找到超簡單的方法,接 IPWHOIS.IO 的 API 就搞定了
資訊也相當完整,記錄一下怎麼應用

function ae_whois($ipAddress) {
  $result = file_get_contents('https://ipwho.is/'.$ipAddress);
  // 由於吐回來的是 JSON 格式,所以 decode 他變成 array 才好應用
  return json_decode($result, true);
}

吐回的格式大致如下:
continent => 地區
country => 國家
city => 城市
差不多可以應用的參數都取的到,非常厲害

{
ip: "xxx.xxx.xxx.xxx", // 這裡就隱藏啦
success: true,
type: "IPv4",
continent: "Asia",
continent_code: "AS",
country: "Taiwan",
country_code: "TW",
region: "Keelung City",
region_code: "KEE",
city: "Taipei",
latitude: xx.xxxxxxx,
longitude: xxx.xxxxxxx,
is_eu: false,
postal: "11008",
calling_code: "886",
capital: "Taipei",
borders: "",
flag: {
img: "https://cdn.ipwhois.io/flags/tw.svg",
emoji: "會顯示國旗圖",
emoji_unicode: "U+1F1F9 U+1F1FC"
},
connection: {
asn: 3462,
org: "Chunghwa Telecom CO.,LTD.",
isp: "Chunghwa Telecom Co., Ltd.",
domain: "logitech.com"
},
timezone: {
id: "Asia/Taipei",
abbr: "CST",
is_dst: false,
offset: 28800,
utc: "+08:00",
current_time: "2023-11-18T13:27:45+08:00"
}
}

標籤: #PHP