使用MaxMind 根据IP地址对访问者定位_PHP

php.cn
Release: 2016-06-01 12:28:13
original
1276 people have browsed it

IP地址

有时你需要知道你的站点访问者来自哪个国家——比如如果你正打算执行针对地理区域的广告计划。本文将对此方法进行介绍。

有时你需要知道你的站点访问者来自哪个国家——比如如果你正打算执行针对地理区域的广告计划。这正是象MaxMind's GeoIP一类的工具大显身手的地方——它可以让你从访问者的IP地址轻松获取其确切的地理位置信息。

MaxMind提供了商业数据库和免费数据库。前者更为精确,精度可以达使用者所在城市信息一级,而后者则只能确定国家和地区。在本文中,我们将演示免费版的使用方法。如果你需要更多详细信息,比如远程客户的城市以及国家信息,你需要从MaxMind:http://www.maxmind.com购买更详细的数据库。

起步

要使用此软件,你必须首先下载GeoIP免费国家信息文件:http://www.maxmind.com/app/geoip_country 并将其存放于Web服务器的某个目录中。然后你需要选择数据库文件所使用的语言API。为简化整个过程,我们将使用纯粹的PHP版本以避免其他额外的配置或设置Apache组件。请记住在安装软件到Web站点前阅读软件许可证条款:http://www.maxmind.com/download/geoip/database/LICENSE.txt以确保你同意这些条款。

代码列表A

// include functions

include("geoip.inc");

// read GeoIP database

$handle = geoip_open("GeoIP.dat", GEOIP_STANDARD);

// map IP to country

echo "IP address 62.149.130.132 located in " . geoip_country_name_by_addr($handle, "62.149.130.132") . " (country code " . geoip_country_code_by_addr($handle, "62.149.130.132") . ")";

// close database handler
// www.knowsky.com

geoip_close($handle);

// print compulsory license notice

echo "

-- This product includes GeoIP data created by MaxMind, available from http://maxmind.com/ --";

?>

列表A中的代码显示了使用模块(geoip.inc)以访问GeoIP免费国家信息数据库(GeoIP.dat)的基本方法。示例假设PHP include和国家家信息数据库文件都在与PHP文件本身相同的目录中。如果示例与你的安装不同,则需要根据需要改变路径。

示例代码相当明了,在引入GeoIP PHP函数库后,第一步即使用geoip_open()函数打开GeoIP数据库文件。此函数接收两个参数:数据库文件路径和数据库类型。

我们然后使用由调用geoip_open()返回的句柄,由此根据所给的IP地址以获取两字母的国家代码及直观的国家名称。其中还要分别借助函数geoip_country_code_by_addr()和geoip_country_code_by_name()。二者都接收两个参数:由geoip_open()返回的句柄以及需要解析的IP地址。

一旦获得所需信息,我们通过调用geoip_close()关闭数据库文件。

所做的就是这么简单。

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!