我想从访问者的IP地址中检索他们的城市、州和国家等信息,这样我就可以根据他们的位置定制我的网页。在PHP中是否有一种好的、可靠的方法来做到这一点?我使用JavaScript作为客户端脚本,PHP作为服务器端脚本,MySQL作为数据库。
当前回答
假设您想自己做而不依赖于其他提供者,IP2Nation提供了一个映射的MySQL数据库,该数据库会随着区域注册中心的变化而更新。
其他回答
我已经用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
如果您需要从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
}
使用谷歌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>
PHP对此有一个扩展。
从PHP.net:
GeoIP扩展允许您查找IP地址的位置。 城市,州,国家,经度,纬度和其他信息为 所有的,如ISP和连接类型可以得到的帮助 GeoIP。
例如:
$record = geoip_record_by_name($ip);
echo $record['city'];
执行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并说它是最好的,但我花了很长时间分析现有的解决方案,他们的解决方案真的很有前途。
推荐文章
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 从IP地址获取位置
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']
- 更好的方法检查变量为null或空字符串?
- 当使用Composer的开发/生产开关时,如何正确部署?
- 自动删除Laravel (Eloquent ORM)中的相关行
- 在取消设置元素后重新设置数组键
- 如何修剪空白的数组值在php
- PHP中的双not(!!)操作符