您的位置:首页 > 编程语言 > PHP开发

【转】GeoIP + PHP 完全指南

2011-03-08 19:15 302 查看
转自:http://www.21andy.com/blog/20100405/1799.html

有2种标准方法来使用 GeoIP



第一种方法:
先下载 GeoIP 数据文件

wget -c http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz gunzip GeoIP.dat.gz 接着下载 GeoIP 的 PHP 文件,保存为 geoip.php
http://geolite.maxmind.com/download/geoip/api/php/geoip.inc

好了,直接使用

<?php

//计时开始
function utime() {
$time = explode( " ", microtime() );
$usec = (double)$time[0];
$sec = (double)$time[1];
return $usec + $sec;
}
$startTimes = utime();

// include the php script
// wget -c http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz // gunzip GeoIP.dat.gz
include("geoip.php");

// open the geoip database
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);

// 获取国家代码
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
echo "Your country code is: <strong>$country_code</strong> <br />";

// 获取国家名称
$country_name = geoip_country_name_by_addr($gi, $_SERVER['REMOTE_ADDR']);
echo "Your country name is: <strong>$country_name</strong> <br />";

// close the database
geoip_close($gi);

//运行结束时间
$endTimes = utime();
$runTimes = sprintf( '%0.4f', ( $endTimes - $startTimes ) );
echo "Processed in " . $runTimes . "second.";
?> 此方法使用二进制文件做为数据库,速度很快,不需要数据库。我试了执行时间是0.001,每秒完成1000次不成问题。



第二种方法:
把 GeoIP 安装成 PHP 扩展

yum install GeoIP GeoIP-data GeoIP-devel 下载 GeoIP 数据库

wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz gzip -d GeoLiteCity.dat.gz
mv GeoLiteCity.dat /var/lib/GeoIP/GeoIPCity.dat 下载 GeoIP 的 PECL 扩展
下载地址 http://pecl.php.net/package/geoip

wget -c http://pecl.php.net/get/geoip-1.0.7.tgz tar -zxvf geoip-1.0.7.tgz 安装 GeoIP 的 PECL 扩展

cd geoip-1.0.7
/usr/bin/phpize
./configure --with-php-config=/usr/bin/php-config --with-geoip
make
make install 在 php.ini 里加上

extension=geoip.so 接着重启一下 php 就行了

service httpd restart 现在,你可以使用 php 手册里的 GeoIP 部份函数了
http://cn.php.net/manual/en/book.geoip.php
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: