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


当前回答

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

其他回答

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

PHP对此有一个扩展。

从PHP.net:

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

例如:

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

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

下面是我发现的使用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" }

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