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


当前回答

我用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);

其他回答

我已经用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

你需要使用外部服务…例如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。

执行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并说它是最好的,但我花了很长时间分析现有的解决方案,他们的解决方案真的很有前途。

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

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