Home >Backend Development >PHP Tutorial >php使用GeoIP库实例_PHP

php使用GeoIP库实例_PHP

WBOY
WBOYOriginal
2016-06-01 11:51:261108browse

需要注意的是maxmind是geoip数据库的提供方,
同时也提供了很多语言的sample和api说明文档。
比如php,和php的geoip库是有很大区别的,包含使用方式,接口函数。
php官方的geoip需要配置php环境,加载geoip.dll库,并在php.ini中指定GEOIP库地址。
maxmind提供一系列 .inc 和 .php 对环境无依赖,只要支持php,直接require后即可使用。

一、GEOIP数据库

http://dev.maxmind.com/geoip/geolite
细分到国家:GeoLite Country
细分到城市:GeoLite City

二、php官方geoip.dll库

下载dll http://windows.php.net/downloads/pecl/releases/geoip/1.0.8/
修改php.ini,启用geoip库:
复制代码 代码如下:extension=php_geoip.dll
追加geoip段,指定数据库位置:
复制代码 代码如下:[geoip]
geoip.custom_directory = "D:\php5.3\geo\"

测试代码

注意geoip.dll中使用的 GeoIPCity.dat 即 GeoLiteCity.dat,用的时候注意看提示
复制代码 代码如下:
echo geoip_country_name_by_name( "8.8.8.8" ) . "\n";
print_r( geoip_record_by_name( "8.8.8.8" ) );
echo geoip_country_name_by_name( "61.139.2.69" ). "\n";
print_r( geoip_record_by_name(  "61.139.2.69" ) );

三、MaxMind官方php文件函数库

文档和示例:http://dev.maxmind.com/geoip/downloadable
修改maxmind示例中 sample.php 和 sample_city.php 中 GeoIP.dat/GeoLiteCity.dat 路径为你自己的路径
同一目录用 “./GeoIP.dat” 或 “./GeoLiteCity.dat” 即可。
详细到国家
复制代码 代码如下:
include("geoip.inc");
$gi = geoip_open( "./GeoIP.dat", GEOIP_STANDARD );
echo geoip_country_code_by_addr($gi, "8.8.8.8") . "\t" . geoip_country_name_by_addr($gi, "8.8.8.8") . "\n";
echo geoip_country_code_by_addr($gi, "61.139.2.69") . "\t" . geoip_country_name_by_addr($gi, "61.139.2.69") . "\n";
geoip_close($gi);

详细到国家城市

复制代码 代码如下:
include("geoipcity.inc");
include("geoipregionvars.php");
$gi = geoip_open("./GeoLiteCity.dat",GEOIP_STANDARD);
 
$record = geoip_record_by_addr($gi,"8.8.8.8");
print $record->country_code . " " . $record->country_code3 . " " . $record->country_name . "\n";
print $record->region . " " . $GEOIP_REGION_NAME[$record->country_code][$record->region] . "\n";
print $record->city . "\n";
print $record->postal_code . "\n";
print $record->latitude . "\n";
print $record->longitude . "\n";
print $record->metro_code . "\n";
print $record->area_code . "\n";
print $record->continent_code . "\n";
 
print "\n-----\n";
$record = geoip_record_by_addr($gi,"61.139.2.69");
print $record->country_code . " " . $record->country_code3 . " " . $record->country_name . "\n";
print $record->region . " " . $GEOIP_REGION_NAME[$record->country_code][$record->region] . "\n";
print $record->city . "\n";
print $record->postal_code . "\n";
print $record->latitude . "\n";
print $record->longitude . "\n";
print $record->metro_code . "\n";
print $record->area_code . "\n";
print $record->continent_code . "\n";
geoip_close($gi);

看自己开发环境和具体情况决定用哪种

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn