Home > Backend Development > PHP Tutorial > geoip+php示范:通过ip,获取国家名称和代码

geoip+php示范:通过ip,获取国家名称和代码

WBOY
Release: 2016-06-13 12:16:17
Original
1109 people have browsed it

geoip+php示例:通过ip,获取国家名称和代码
GeoIP + PHP的使用


方法一:


下载 GeoIP 的 PHP 文件geoip.inc,保存为 geoip.inc.php


http://sjolzy.cn/php/GeoIP/bak/geoip.inc


php使用代码


<?phpinclude ("geoip.inc.php");$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);$country_code = geoip_country_code_by_addr($gi, $_SERVER[&#39;REMOTE_ADDR&#39;]);$country_name = geoip_country_name_by_addr($gi, $_SERVER[&#39;REMOTE_ADDR&#39;]);geoip_close($gi);$jsonEcho = array();$jsonEcho["error"] = 0;$jsonEcho["country_code"] = $country_code;$jsonEcho["country_name"] = $country_name;function jsonp($object, $callback = &#39;callback&#39;) {		if (!empty($_GET[$callback])) {			header(&#39;Content-Type: application/x-javascript&#39;);		} else {						header(&#39;Content-Type: application/json&#39;);		}		return $_GET[$callback].&#39;(&#39;.json_encode($object).&#39;)&#39;;}echo jsonp($jsonEcho);?>
Copy after login

注:在本地测试的话因 为$_SERVER['REMOTE_ADDR']和$_SERVER['REMOTE_ADDR']可能是127.0.0.1,所 以输出的内容为空。可以自己带入IP测试


方法二:

把 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/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-geoip
make
make install


在 php.ini 里加上 
extension=geoip.so


接着重启一下 php 就行了(nginx+php的情况,而apache+php就不用重启了)
现在,你可以使用 php 手册里的 GeoIP 部份函数了
http://cn.php.net/manual/en/book.geoip.php


参考:http://blog.csdn.net/prince2270/article/details/4592753




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 admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template