我想从访问者的IP地址中检索他们的城市、州和国家等信息,这样我就可以根据他们的位置定制我的网页。在PHP中是否有一种好的、可靠的方法来做到这一点?我使用JavaScript作为客户端脚本,PHP作为服务器端脚本,MySQL作为数据库。


你需要使用外部服务…例如http://www.hostip.info/,如果你谷歌搜索“geo-ip”,你可以得到更多的结果。

主机ip API是基于HTTP的,因此您可以根据需要在PHP或JavaScript中使用它。


查看来自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...

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


假设您想自己做而不依赖于其他提供者,IP2Nation提供了一个映射的MySQL数据库,该数据库会随着区域注册中心的变化而更新。


我喜欢Maxmind的免费GeoLite City,它最适用 如果它不够精确,你可以从它升级到付费版本。包括一个PHP API,以及其他语言的API。如果你将Lighttpd作为web服务器运行,你甚至可以使用一个模块为每个访问者获取SERVER变量中的信息,如果这是你所需要的。

我应该补充的是,还有一个免费的Geolite Country(如果你不需要确定IP来自哪个城市,这个会更快)和Geolite ASN(如果你想知道谁拥有IP),最后所有这些都可以在你自己的服务器上下载,每月更新一次,使用提供的api可以非常快地查找,因为他们说“每秒数千次查找”。


PHP对此有一个扩展。

从PHP.net:

GeoIP扩展允许您查找IP地址的位置。 城市,州,国家,经度,纬度和其他信息为 所有的,如ISP和连接类型可以得到的帮助 GeoIP。

例如:

$record = geoip_record_by_name($ip);
echo $record['city'];

使用谷歌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>

我想我张贴,因为似乎没有人给这个特定的API的信息,但它返回的正是我所追求的,你可以让它以多种格式返回,json, xml和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": ""

}

您可以下载免费的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>


下面是我发现的使用http://ipinfodb.com/ip_locator.php获取信息的代码片段的修改版本。请记住,您还可以使用它们申请API密钥,并直接使用API来获得您认为合适的信息。

片段

function detect_location($ip=NULL, $asArray=FALSE) {
    if (empty($ip)) {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }
        else { $ip = $_SERVER['REMOTE_ADDR']; }
    }
    elseif (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') {
        $ip = '8.8.8.8';
    }

    $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
    $i = 0; $content; $curl_info;

    while (empty($content) && $i < 5) {
        $ch = curl_init();
        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_URL => $url,
            CURLOPT_TIMEOUT => 1,
            CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
        );
        if (isset($_SERVER['HTTP_USER_AGENT'])) $curl_opt[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
        curl_setopt_array($ch, $curl_opt);
        $content = curl_exec($ch);
        if (!is_null($curl_info)) $curl_info = curl_getinfo($ch);
        curl_close($ch);
    }

    $araResp = array();
    if (preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs)) $araResp['city'] = trim($regs[1]);
    if (preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs)) $araResp['state'] = trim($regs[1]);
    if (preg_match('{<li>Country : ([^<]*)}i', $content, $regs)) $araResp['country'] = trim($regs[1]);
    if (preg_match('{<li>Zip or postal code : ([^<]*)</li>}i', $content, $regs)) $araResp['zip'] = trim($regs[1]);
    if (preg_match('{<li>Latitude : ([^<]*)</li>}i', $content, $regs)) $araResp['latitude'] = trim($regs[1]);
    if (preg_match('{<li>Longitude : ([^<]*)</li>}i', $content, $regs)) $araResp['longitude'] = trim($regs[1]);
    if (preg_match('{<li>Timezone : ([^<]*)</li>}i', $content, $regs)) $araResp['timezone'] = trim($regs[1]);
    if (preg_match('{<li>Hostname : ([^<]*)</li>}i', $content, $regs)) $araResp['hostname'] = trim($regs[1]);

    $strResp = ($araResp['city'] != '' && $araResp['state'] != '') ? ($araResp['city'] . ', ' . $araResp['state']) : 'UNKNOWN';

    return $asArray ? $araResp : $strResp;
}

使用

detect_location();
//  returns "CITY, STATE" based on user IP

detect_location('xxx.xxx.xxx.xxx');
//  returns "CITY, STATE" based on IP you provide

detect_location(NULL, TRUE);    //   based on user IP
//  returns array(8) { ["city"] => "CITY", ["state"] => "STATE", ["country"] => "US", ["zip"] => "xxxxx", ["latitude"] => "xx.xxxxxx", ["longitude"] => "-xx.xxxxxx", ["timezone"] => "-07:00", ["hostname"] => "xx-xx-xx-xx.host.name.net" }

detect_location('xxx.xxx.xxx.xxx', TRUE);   //   based on IP you provide
//  returns array(8) { ["city"] => "CITY", ["state"] => "STATE", ["country"] => "US", ["zip"] => "xxxxx", ["latitude"] => "xx.xxxxxx", ["longitude"] => "-xx.xxxxxx", ["timezone"] => "-07:00", ["hostname"] => "xx-xx-xx-xx.host.name.net" }

你亦可使用“smart-ip”服务:

$.getJSON("http://smart-ip.net/geoip-json?callback=?",
    function (data) {
        alert(data.countryName);
        alert(data.city);
    }
);

本·道林回复中的服务已经改变了,所以现在更简单了。要找到位置,只需做:

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

坐标以单一字符串形式返回,如'31,-80',因此从那里你只需:

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

我已经用IP地址服务做了很多测试,下面是我自己做的一些方法。 首先是一些我使用的有用网站的链接:

https://db-ip.com/db 有一个免费的ip查找服务和有一些免费的csv文件你可以 下载。这使用一个免费的api密钥,是附加到您的电子邮件。它限制每天查询2000次。

http://ipinfo.io/ 免费的ip查找服务,没有api键 PHP函数:

//uses http://ipinfo.io/.
function ip_visitor_country($ip){
    $ip_data_in = get_web_page("http://ipinfo.io/".$ip."/json"); //add the ip to the url and retrieve the json data
    $ip_data = json_decode($ip_data_in['content'],true); //json_decode it for php use

    //this ip-lookup service returns 404 if the ip is invalid/not found so return false if this is the case.
    if(empty($ip_data) || $ip_data_in['httpcode'] == 404){
        return false;
    }else{
        return $ip_data; 
    }
}

function get_web_page($url){
    $user_agent = 'Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';

    $options = array(
        CURLOPT_CUSTOMREQUEST  =>"GET",        //set request type post or get
        CURLOPT_POST           =>false,        //set to GET
        CURLOPT_USERAGENT      => $user_agent, //set user agent
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    );
    $ch = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    $httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
    curl_close( $ch );  
    $header['errno']   = $err; //curl error code
    $header['errmsg']  = $errmsg; //curl error message
    $header['content'] = $content; //the webpage result (In this case the ip data in json array form)
    $header['httpcode'] = $httpCode; //the webpage response code
    return $header; //return the collected data and response codes
}

最后你会得到这样的结果:

Array
(
    [ip] => 1.1.1.1
    [hostname] => No Hostname
    [city] => 
    [country] => AU
    [loc] => -27.0000,133.0000
    [org] => AS15169 Google Inc.
)

http://www.geoplugin.com/ 稍微有点老,但这项服务给你一大堆额外有用的信息,如货币离开国家,大陆代码,经度等。


http://lite.ip2location.com/database-ip-country-region-city-latitude-longitude 提供了一堆可下载的文件,并附有将它们导入数据库的说明。 一旦在数据库中有了这些文件中的一个,就可以相当容易地选择数据。

SELECT * FROM `ip2location_db5` WHERE IP > ip_from AND IP < ip_to

使用php函数ip2long();将ip-address转换为数值。例如,1.1.1.1变成16843009。这允许您扫描数据库文件提供给您的ip范围。

因此,为了找出1.1.1.1属于哪里,我们所要做的就是运行这个查询:

SELECT * FROM `ip2location_db5` WHERE 16843009 > ip_from AND 16843009 < ip_to;

这将返回此数据作为示例。

FROM: 16843008
TO: 16843263
Country code: AU
Country: Australia
Region: Queensland
City: Brisbane
Latitude: -27.46794
Longitude: 153.02809

我用ipapi写了一个机器人。下面是如何在php中获取IP地址(例如1.2.3.4)的location:

设置报头:

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

获取JSON响应

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

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

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

这个问题是保密的,我知道。然而,我在这里没有看到答案,我看到的是很多人展示了他们从同样的问题中得出的答案。

目前有五个具有不同程度功能的区域互联网注册中心作为与知识产权所有权有关的第一个接触点。这个过程是不断变化的,这就是为什么这里的各种服务有时工作,有时不工作的原因。

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

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

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

人们不喜欢自己被跟踪的概念,所以——我的想法是——直接从你的客户那里得到信息,并得到他们的许可,并期望很多人对这个概念有所回避。


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

JSON: https://geolocation-db.com/json JSONP-callback: https://geolocation-db.com/jsonp

不需要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://geolocation-db.com/json/geoip.php?jsonp=callback'; var h = document.getElementsByTagName('script')[0]; h.parentNode.insertBefore(script, h); </script> </html>


如果有人无意中发现了这个问题,这里有另一个解决方案。在timezoneapi。I . io你可以请求一个IP地址并返回几个对象(我已经创建了服务)。创建它是因为我需要知道我的用户在哪个时区,在世界的哪个地方,以及现在是什么时间。

在PHP中-返回位置,时区和日期/时间:

// Get IP address
$ip_address = getenv('HTTP_CLIENT_IP') ?: getenv('HTTP_X_FORWARDED_FOR') ?: getenv('HTTP_X_FORWARDED') ?: getenv('HTTP_FORWARDED_FOR') ?: getenv('HTTP_FORWARDED') ?: getenv('REMOTE_ADDR');

// Get JSON object
$jsondata = file_get_contents("http://timezoneapi.io/api/ip/?" . $ip_address);

// Decode
$data = json_decode($jsondata, true);

// Request OK?
if($data['meta']['code'] == '200'){

    // Example: Get the city parameter
    echo "City: " . $data['data']['city'] . "<br>";

    // Example: Get the users time
    echo "Time: " . $data['data']['datetime']['date_time_txt'] . "<br>";

}

使用jQuery:

// Get JSON object
$.getJSON('https://timezoneapi.io/api/ip', function(data){

    // Request OK?
    if(data.meta.code == '200'){

        // Log
        console.log(data);

        // Example: Get the city parameter
        var city = data.data.city;
        alert(city);

        // Example: Get the users time
        var time = data.data.datetime.date_time_txt;
        alert(time);

    }

});

如果您需要从IP地址获取位置,您可以使用可靠的地理IP服务,您可以在这里获得更多详细信息。支持IPv6。

作为奖励,它允许检查ip地址是否tor节点,公共代理或垃圾邮件。

你可以使用javascript或php如下所示。

Javascript代码:

$(document).ready(function () {
        $('#btnGetIpDetail').click(function () {
            if ($('#txtIP').val() == '') {
                alert('IP address is reqired');
                return false;
            }
            $.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
                 function (result) {
                     alert('City Name: ' + result.city)
                     console.log(result);
                 });
        });
    });

Php代码:

$result = json_decode(file_get_contents('http://ip-api.io/json/64.30.228.118'));
var_dump($result);

输出:

{
"ip": "64.30.228.118",
"country_code": "US",
"country_name": "United States",
"region_code": "FL",
"region_name": "Florida",
"city": "Fort Lauderdale",
"zip_code": "33309",
"time_zone": "America/New_York",
"latitude": 26.1882,
"longitude": -80.1711,
"metro_code": 528,
"suspicious_factors": {
"is_proxy": false,
"is_tor_node": false,
"is_spam": false,
"is_suspicious": false
}

Ipdata。co是一个快速、高可用的IP地理定位API,性能可靠。

它具有极高的可扩展性,在世界各地有10个端点,每个端点每秒可以处理>万个请求!

这个答案使用了一个非常有限的“测试”API键,仅用于测试几个调用。注册您自己的免费API密钥,每天最多可获得1500个开发请求。

在php中

php > $ip = '8.8.8.8';
php > $details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}?api-key=test"));
php > echo $details->region;
California
php > echo $details->city;
Mountain View
php > echo $details->country_name;
United States
php > echo $details->latitude;
37.751

下面是一个客户端示例,展示了如何获取国家、地区和城市;

$ . get (" https://api.ipdata.co?Api-key =test",函数(响应){ $(" #反应”). html (JSON。Stringify(响应,null, 4)); $("#country").html(' country: ' + response.country_name); $("#region").html(' region ' + response.region); $("#city").html(' city ' + response.city); }, " jsonp "); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < div id = "国家" > < / div > < div id = "地区" > < / div > < div id = "城市" > < / div > < pre id =“响应”> < / >之前

免责声明;

我创建了这项服务。

有关多种语言的示例,请参阅文档

还可以查看最佳IP地理定位api的详细分析。


我在IPLocate上运行服务。Io,你可以通过一个简单的电话免费连接到它:

<?php
$res = file_get_contents('https://www.iplocate.io/api/lookup/8.8.8.8');
$res = json_decode($res);

echo $res->country; // United States
echo $res->continent; // North America
echo $res->latitude; // 37.751
echo $res->longitude; // -97.822

var_dump($res);

$res对象将包含您的地理位置字段,如国家、城市等。

查看文档了解更多信息。


执行IP地理定位有两种广泛的方法:一种是下载数据集,将其托管在基础设施上并保持最新。这需要时间和精力,特别是当您需要支持大量请求时。另一种解决方案是使用现有的API服务来为您管理所有工作。

有许多API地理定位服务:Maxmind, Ip2location, Ipstack, IpInfo等。最近,我工作的公司已经切换到Ipregistry (https://ipregistry.co),我参与了决策和实施过程。下面是一些你在寻找IP地理定位API时应该考虑的元素:

服务准确吗?他们是否使用单一的信息来源? 他们真的能承受你的负担吗? 它们是否在全球范围内提供一致且快速的响应时间(除非您的用户是特定国家的用户)? 他们的定价模式是什么?

下面是一个获取IP地理位置信息的例子(还包括威胁和用户代理数据,使用一个调用):

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("https://api.ipregistry.co/{$ip}?key=tryout"));
echo $details->location;

注:我不是在这里推广Ipregistry并说它是最好的,但我花了很长时间分析现有的解决方案,他们的解决方案真的很有前途。