获取客户端IP,然后从中获取城市名称[重复]
Posted
技术标签:
【中文标题】获取客户端IP,然后从中获取城市名称[重复]【英文标题】:Getting client IP and then city name from it [duplicate] 【发布时间】:2013-11-26 09:04:12 【问题描述】:在这里,当他单击我页面上的登录按钮时,我试图获取用户的 IP。我想最终从IP中得到city
的名字。
function get_client_ip()
$ipaddress = '';
if ($_SERVER['HTTP_CLIENT_IP'])
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if($_SERVER['HTTP_X_FORWARDED_FOR'])
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if($_SERVER['HTTP_X_FORWARDED'])
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if($_SERVER['HTTP_FORWARDED_FOR'])
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if($_SERVER['HTTP_FORWARDED'])
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if($_SERVER['REMOTE_ADDR'])
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
除了上述之外,还有什么更好更快的方法吗?
然后得到城市,
$ip = get_client_ip();
$details = json_decode(file_get_contents("http://ipinfo.io/$ip"));
echo $details->city;
【问题讨论】:
您可以下载与城市相关的ip范围并将它们存储在db中,这样您就可以根据本地db中的范围测试ip,执行起来会更快,但我不认为努力值得 【参考方案1】:<?php
require_once("userip/ip.codehelper.io.php");
require_once("userip/php_fast_cache.php");
$_ip = new ip_codehelper();
$real_client_ip_address = $_ip->getRealIP();
$visitor_location = $_ip->getLocation($real_client_ip_address);
$guest_ip = $visitor_location['IP'];
$guest_country = $visitor_location['CountryName'];
$guest_city = $visitor_location['CityName'];
$guest_state = $visitor_location['RegionName'];
echo "IP Address: ". $guest_ip. "<br/>";
echo "Country: ". $guest_country. "<br/>";
echo "State: ". $guest_state. "<br/>";
echo "City: ". $guest_city. "<br/>";
?>
详情请看这里http://www.a2zwebhelp.com/visitor-location-in-php
【讨论】:
如果您使用的是图书馆,您不应该提供链接吗?在哪里下载? 以上链接有下载链接以上是关于获取客户端IP,然后从中获取城市名称[重复]的主要内容,如果未能解决你的问题,请参考以下文章