我想从访问者的IP地址中检索城市、州和国家等信息,这样我就可以根据他们的位置自定义我的网页。在PHP中有没有一种既好又可靠的方法来做到这一点呢?我使用JavaScript编写客户端脚本,使用PHP编写服务器端脚本,使用MySQL编写数据库。
发布于 2013-07-26 01:13:47
您可以下载免费的GeoIP数据库并在本地查找IP地址,也可以使用第三方服务并执行远程查找。这是更简单的选择,因为它不需要设置,但它确实引入了额外的延迟。
你可以使用的第三方服务是我的,http://ipinfo.io。它们提供主机名、地理位置、网络所有者和其他信息,例如:
$ curl ipinfo.io/8.8.8.8
{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"loc": "37.385999999999996,-122.0838",
"org": "AS15169 Google Inc.",
"city": "Mountain View",
"region": "CA",
"country": "US",
"phone": 650
}
下面是一个PHP示例:
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo $details->city; // -> "Mountain View"
你也可以在客户端使用它。下面是一个简单的jQuery示例:
$.get("https://ipinfo.io/json", function (response) {
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>Client side IP geolocation using <a href="http://ipinfo.io">ipinfo.io</a></h3>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>
发布于 2013-05-16 22:05:44
我想我会发布,因为似乎没有人给出关于这个特定接口的信息,但它返回的正是我想要的,你可以让它以多种格式返回,json, xml and csv
。
$location = file_get_contents('http://freegeoip.net/json/'.$_SERVER['REMOTE_ADDR']);
print_r($location);
这将为您提供您可能想要的所有东西:
{
"ip": "77.99.179.98",
"country_code": "GB",
"country_name": "United Kingdom",
"region_code": "H9",
"region_name": "London, City of",
"city": "London",
"zipcode": "",
"latitude": 51.5142,
"longitude": -0.0931,
"metro_code": "",
"areacode": ""
}
发布于 2012-08-24 02:20:38
使用Google APIS:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script>
contry_code = google.loader.ClientLocation.address.country_code
city = google.loader.ClientLocation.address.city
region = google.loader.ClientLocation.address.region
</script>
https://stackoverflow.com/questions/409999
复制相似问题