从 IP 地址获取位置 [英] Getting the location from an IP address

查看:29
本文介绍了从 IP 地址获取位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从访问者的 IP 地址检索诸如城市、州和国家/地区之类的信息,以便我可以根据他们的位置自定义我的网页.在 PHP 中是否有一种很好且可靠的方法来做到这一点?我使用 JavaScript 编写客户端脚本,使用 PHP 编写服务器端脚本,使用 MySQL 编写数据库.

I want to retrieve information like the city, state, and country of a visitor from their IP address, so that I can customize my web page according to their location. Is there a good and reliable way to do this in PHP? I am using JavaScript for client-side scripting, PHP for server-side scripting, and MySQL for the database.

推荐答案

您可以下载免费的 GeoIP 数据库并在本地查找 IP 地址,或者您可以使用第三方服务并执行远程查找.这是更简单的选项,因为它不需要设置,但会引入额外的延迟.

You could download a free GeoIP database and lookup the IP address locally, or you could use a third party service and perform a remote lookup. This is the simpler option, as it requires no setup, but it does introduce additional latency.

您可以使用的第三方服务是我的,http://ipinfo.io.它们提供主机名、地理位置、网络所有者和其他信息,例如:

One third party service you could use is mine, http://ipinfo.io. They provide hostname, geolocation, network owner and additional information, eg:

$ 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 示例:

Here's a PHP example:

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo $details->city; // -> "Mountain View"

您也可以在客户端使用它.这是一个简单的 jQuery 示例:

You can also use it client-side. Here's a simple jQuery example:

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

这篇关于从 IP 地址获取位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆