我想从访问者的IP地址中检索他们的城市、州和国家等信息,这样我就可以根据他们的位置定制我的网页。在PHP中是否有一种好的、可靠的方法来做到这一点?我使用JavaScript作为客户端脚本,PHP作为服务器端脚本,MySQL作为数据库。
当前回答
一个纯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>
其他回答
使用谷歌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>
你需要使用外部服务…例如http://www.hostip.info/,如果你谷歌搜索“geo-ip”,你可以得到更多的结果。
主机ip API是基于HTTP的,因此您可以根据需要在PHP或JavaScript中使用它。
下面是我发现的使用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>
查看来自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(!!)操作符