我想从访问者的IP地址中检索他们的城市、州和国家等信息,这样我就可以根据他们的位置定制我的网页。在PHP中是否有一种好的、可靠的方法来做到这一点?我使用JavaScript作为客户端脚本,PHP作为服务器端脚本,MySQL作为数据库。
当前回答
如果您需要从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
}
其他回答
本·道林回复中的服务已经改变了,所以现在更简单了。要找到位置,只需做:
// 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
下面是我发现的使用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" }
一个纯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);
}
});
查看来自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。
推荐文章
- 如何将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(!!)操作符