如何根据IP确定用户的当前位置(我猜它是这样的。)
答案 0 :(得分:29)
<?php
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$country = $geo["geoplugin_countryName"];
$city = $geo["geoplugin_city"];
?>
答案 1 :(得分:21)
<强>被修改强>
<?php
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$PublicIP = get_client_ip();
$json = file_get_contents("http://ipinfo.io/$PublicIP/geo");
$json = json_decode($json ,true);
$country = $json['country'];
$region= $json['region'];
$city = $json['city'];
?>
答案 2 :(得分:9)
使用hostip.info服务尝试此代码:
$country=file_get_contents('http://api.hostip.info/get_html.php?ip=');
echo $country;
// Reformat the data returned (Keep only country and country abbr.)
$only_country=explode (" ", $country);
echo "Country : ".$only_country[1]." ".substr($only_country[2],0,4);
答案 3 :(得分:9)
// check item[]= is repeated four times
if(substr_count($list, "item[]=") == '4') {
// strip the string to only numbers, then will need to check each number if between 1-4
$numbers = preg_replace("/[^0-9]/","",$list);
// strip the string to only numbers and the character after it, will need to ensure it is & (except for the last number)
preg_replace("/[^0-9]/","",$list + 1);
}
使用此来源尝试此代码。它有效!
答案 4 :(得分:4)
MaxMind GeoIP是一项很好的服务。他们还提供免费的城市级查询服务。
答案 5 :(得分:3)
您可能需要查看GeoIP Country Whois Locator处的PHPClasses。
答案 6 :(得分:2)
答案 7 :(得分:0)
IP为您提供了一个非常不可靠的位置,如果首先拥有该位置并不重要,您可以使用JS加载Ajax位置。 (此外,用户需要授予您访问权限的权限。)
答案 8 :(得分:-1)
旧的freegeoip API现已弃用,将于2018年7月1日停止使用。
新API来自{{3}}。您必须在ipstack中创建帐户。然后您可以使用API网址中的访问密钥。
$url = "http://api.ipstack.com/122.167.180.20?access_key=ACCESS_KEY&format=1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
$city = $response->city; //You can get all the details like longitude,latitude from the $response .
有关详情,请点击此处:/ https://ipstack.com