【发布时间】:2011-07-20 21:34:05
【问题描述】:
如何根据IP判断用户当前位置(我猜是这样)。
【问题讨论】:
标签: php geolocation ip
如何根据IP判断用户当前位置(我猜是这样)。
【问题讨论】:
标签: php geolocation ip
<?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"];
?>
【讨论】:
已编辑
<?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'];
?>
【讨论】:
if(isset(HTTP_X_FORWARDED_FOR))。
<?php
$query = @unserialize (file_get_contents('http://ip-api.com/php/'));
if ($query && $query['status'] == 'success') {
echo 'Hey user from ' . $query['country'] . ', ' . $query['city'] . '!';
}
foreach ($query as $data) {
echo $data . "<br>";
}
?>
使用此源尝试此代码。它有效!
【讨论】:
使用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);
【讨论】:
MaxMind GeoIP 服务很好。他们还提供免费的城市级查询服务。
【讨论】:
您可能想查看位于PHPClasses 的GeoIP Country Whois Locator。
【讨论】:
由于PHP依赖服务器,无法提供实时定位,只能提供静态定位,最好避免依赖JS定位,而不是使用php。但是需要将js数据发布到php,以便在服务器上轻松编程
【讨论】:
IP 为您提供了一个非常不可靠的位置,如果最初获取位置并不重要,您可以在加载时使用 JS 对位置进行 Ajax。 (此外,用户需要授予您访问它的权限。)
【讨论】:
旧的 freegeoip API 现已弃用,将于 2018 年 7 月 1 日停用。
新 API 来自 https://ipstack.com。您必须在 ipstack 中创建帐户。然后您可以使用 API url 中的访问密钥。
$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://github.com/apilayer/freegeoip
【讨论】: