http://chir.ag/projects/geoiploc/
您好,我正在尝试对此进行设置,但每当我使用include("geoiploc.php");
时,页面都是空白的,每当我删除include("geoiploc.php");
时,我只会看到我的IP地址。我已经将geoiploc.php和index.php上传到可以运行PHP的webhost。
如果有其他更简单的方式通过IP或任何其他方式显示国家/地区名称,这是什么?我需要这个快速
正如我所说的,每当我删除include("geoiploc.php");
为什么时,它只显示我的IP?
您需要此库:http://chir.ag/projects/geoiploc/autogen/geoiploc.tar.gz这是运行脚本的代码:
include("geoiploc.php"); // Must include this
// ip must be of the form "192.168.1.100"
// you may load this from a database
$ip = $_SERVER["REMOTE_ADDR"];
echo "Your IP Address is: " . $ip . "<br />";
echo "Your Country is: ";
// returns country code by default
echo getCountryFromIP($ip);
echo "<br />\n";
// optionally, you can specify the return type
// type can be "code" (default), "abbr", "name"
echo "Your Country Code is: ";
echo getCountryFromIP($ip, "code");
echo "<br />\n";
// print country abbreviation - case insensitive
echo "Your Country Abbreviation is: ";
echo getCountryFromIP($ip, "AbBr");
echo "<br />\n";
// full name of country - spaces are trimmed
echo "Your Country Name is: ";
echo getCountryFromIP($ip, " NamE ");
echo "<br />\n";
答案 0 :(得分:3)
您可以使用免费的MaxMind Geo Lite。在此处下载文件:http://www.maxmind.com/download/geoip/api/php/php-latest.tar.gz
然后从此处下载地理国家/地区数据库:http://dev.maxmind.com/geoip/legacy/geolite
您现在可以像这样使用它:
<?php
include("geoip.inc");
function ipAddress(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])){ //check ip from share internet
$ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ // proxy pass ip
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$gi = geoip_open("path/to/GeoIP.dat",GEOIP_STANDARD);
echo geoip_country_name_by_addr($gi, ipAddress());
// echo geoip_country_code_by_addr($gi, ipAddress()); <-- country code
geoip_close($gi);
?>
更新:要获取用户的城市,您应该下载顶部链接并查找名为sample_city.php
的文件以查看示例代码。您需要下载此文件:http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz并将其放在与php文件相同的目录中。一个简单的例子是:
<?php
include("geoipcity.inc");
function ipAddress(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])){ //check ip from share internet
$ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ // proxy pass ip
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$gi = geoip_open("GeoIPCity.dat",GEOIP_STANDARD);
$record = geoip_record_by_addr($gi,ipAddress());
print $record->country_code . " " . $record->country_code3 . " " . $record->country_name . "\n";
geoip_close($gi);
?>