php 从 IP 地址获取位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/409999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:39:26  来源:igfitidea点击:

Getting the location from an IP address

phpgeolocationipgeoip

提问by Ben Dowling

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.

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

回答by Ben Dowling

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.

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

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

您可以使用的第三方服务是我的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
}

Here's a PHP example:

这是一个 PHP 示例:

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

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

您也可以在客户端使用它。这是一个简单的 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>

回答by Jamie Hutber

Thought I'd post as nobody seems to have given info on this particular API, but its returning exactly what I'm after and you can get it to return in multiple formats, json, xml and csv.

我以为我会发布,因为似乎没有人提供有关此特定 API 的信息,但它返回的正是我想要的,并且您可以让它以多种格式返回,json, xml and csv.

 $location = file_get_contents('http://freegeoip.net/json/'.$_SERVER['REMOTE_ADDR']);
 print_r($location);

This will give you all of the things you could possibly want:

这将为您提供您可能想要的所有东西:

{
      "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": ""

}

回答by Kurt Van den Branden

A pure Javascript example, using the services of https://geolocation-db.comThey provide a JSON and JSONP-callback solution.

一个纯 Javascript 示例,使用https://geolocation-db.com的服务,他们提供了 JSON 和 JSONP 回调解决方案。

No jQuery required!

不需要jQuery!

<!DOCTYPE html>
<html>
<head>
<title>Geo City Locator by geolocation-db.com</title>
</head>
<body>
    <div>Country: <span id="country"></span></div>
    <div>State: <span id="state"></span></div>
    <div>City: <span id="city"></span></div>
    <div>Postal: <span id="postal"></span></div>
    <div>Latitude: <span id="latitude"></span></div>
    <div>Longitude: <span id="longitude"></span></div>
    <div>IP address: <span id="ipv4"></span></div>                             
</body>
<script>

    var country = document.getElementById('country');
    var state = document.getElementById('state');
    var city = document.getElementById('city');
    var postal = document.getElementById('postal');
    var latitude = document.getElementById('latitude');
    var longitude = document.getElementById('longitude');
    var ip = document.getElementById('ipv4');

    function callback(data)
    {
        country.innerHTML = data.country_name;
        state.innerHTML = data.state;
        city.innerHTML = data.city;
        postal.innerHTML = data.postal;
        latitude.innerHTML = data.latitude;
        longitude.innerHTML = data.longitude;
        ip.innerHTML = data.IPv4;
    }

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://geoilocation-db.com/json/geoip.php?jsonp=callback';
    var h = document.getElementsByTagName('script')[0];
    h.parentNode.insertBefore(script, h);

</script> 
</html>

回答by Raposo

Using Google APIS:

使用谷歌 API:

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

回答by null

You need to use an external service... such as http://www.hostip.info/if you google search for "geo-ip" you can get more results.

您需要使用外部服务...例如http://www.hostip.info/如果您在 google 上搜索“geo-ip”,您可以获得更多结果。

The Host-IP API is HTTP based so you can use it either in PHP or JavaScript depending on your needs.

Host-IP API 基于 HTTP,因此您可以根据需要在 PHP 或 JavaScript 中使用它。

回答by Jaimes

I wrote a bot using an API from ipapi.co, here's how you can get location for an IP address (e.g. 1.2.3.4) in php:

我使用来自ipapi.co的 API 编写了一个机器人,以下是获取 IP 地址(例如1.2.3.4)位置的方法php

Set header :

设置标题:

$opts = array('http'=>array('method'=>"GET", 'header'=>"User-Agent: mybot.v0.7.1"));
$context = stream_context_create($opts);

Get JSON response

获取 JSON 响应

echo file_get_contents('https://ipapi.co/1.2.3.4/json/', false, $context);

of get a specific field (country, timezone etc.)

获取特定字段(国家、时区等)

echo file_get_contents('https://ipapi.co/1.2.3.4/country/', false, $context);

回答by jinzai

This question is protected, which I understand. However, I do not see an answer here, what I see is a lot of people showing what they came up with from having the same question.

这个问题是受保护的,我理解。但是,我在这里没有看到答案,我看到的是很多人展示了他们从同一问题中得出的答案。

There are currently five Regional Internet Registries with varying degrees of functionality that serve as the first point of contact with regard to IP ownership. The process is in flux, which is why the various services here work sometimes and don't at other times.

目前有五个具有不同功能程度的区域互联网注册管理机构,作为知识产权所有权方面的第一联络点。这个过程是不断变化的,这就是为什么这里的各种服务有时有效而其他时候无效的原因。

Who Is is (obviously) an ancient TCP protocol, however -- the way it worked originally was by connection to port 43, which makes it problematic getting it routed through leased connections, through firewalls...etc.

然而,Who Is(显然)是一个古老的 TCP 协议——它最初的工作方式是连接到端口 43,这使得通过租用连接、防火墙等进行路由变得有问题。

At this moment -- most Who Is is done via RESTful HTTP and ARIN, RIPE and APNIC have RESTful services that work. LACNIC's returns a 503 and AfriNIC apparently has no such API. (All have online services, however.)

目前——大多数 Who Is 是通过 RESTful HTTP 完成的,ARIN、RIPE 和 APNIC 都有可用的 RESTful 服务。LACNIC 返回 503,而 AfriNIC 显然没有这样的 API。(不过,所有都有在线服务。)

That will get you -- the address of the IP's registered owner, but -- not your client's location -- you must get that from them and also -- you have to ask for it. Also, proxies are the least of your worries when validating the IP that you think is the originator.

这将为您提供 - IP 注册所有者的地址,但 - 不是您客户的位置 - 您必须从他们那里获得,而且 - 您必须要求它。此外,在验证您认为是发起者的 IP 时,代理是您最不担心的。

People do not appreciate the notion that they are being tracked, so -- my thoughts are -- get it from your client directly and with their permission and expect a lot to balk at the notion.

人们不喜欢他们被跟踪的想法,所以——我的想法是——直接从你的客户那里得到他们的许可,并期望很多人对这个想法犹豫不决。

回答by Isaac Askew

The service in Ben Dowling's response has changed, so it's now simpler. To find the location, simply do:

Ben Dowling 响应中的服务已更改,因此现在更简单。要找到位置,只需执行以下操作:

// no need to pass ip any longer; ipinfo grabs the ip of the person requesting
$details = json_decode(file_get_contents("http://ipinfo.io/"));
echo $details->city; // city

The coordinates return in a single string like '31,-80', so from there you just:

坐标以单个字符串形式返回,例如 '31,-80',因此您只需:

$coordinates = explode(",", $details->loc); // -> '31,-89' becomes'31','-80'
echo $coordinates[0]; // latitude
echo $coordinates[1]; // longitude

回答by Isaac Waller

Look at the API from hostip.info - it provides lots of information.
Example in PHP:

查看 hostip.info 中的 API - 它提供了大量信息。
PHP 中的示例:

$data = file_get_contents("http://api.hostip.info/country.php?ip=12.215.42.19");
//$data contains: "US"

$data = file_get_contents("http://api.hostip.info/?ip=12.215.42.19");
//$data contains: XML with country, lat, long, city, etc...

If you trust hostip.info, it seems to be a very useful API.

如果您信任 hostip.info,它似乎是一个非常有用的 API。

回答by James Cape

Assuming you want to do it yourself and not rely upon other providers, IP2Nationprovides a MySQL database of the mappings which are updated as the regional registries change things around.

假设您想自己完成而不是依赖其他提供商,IP2Nation提供了一个映射的 MySQL 数据库,该数据库随着区域注册表的变化而更新。