Home >Backend Development >PHP Tutorial >geoip+php example: get country name and code through ip

geoip+php example: get country name and code through ip

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-08-08 09:28:191211browse

How to use GeoIP + PHP
Method 1:
Download the PHP file geoip.inc of GeoIP and save it as geoip.inc.php
http://sjolzy.cn/php/GeoIP/bak/geoip.inc

php usage code

<?php
include("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);

?>

Note: When testing locally, $_SERVER['REMOTE_ADDR'] and $_SERVER['REMOTE_ADDR'] may be 127.0.0.1, so the output content is empty. You can bring in the IP test yourself
Method 2:
Install GeoIP as a PHP extension
yum install GeoIP GeoIP-data GeoIP-devel
Download the GeoIP database
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity .dat.gz
gzip -d GeoLiteCity.dat.gz
mv GeoLiteCity.dat /var/lib/GeoIP/GeoIPCity.dat
Download the PECL extension for GeoIP
Download address 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
Install GeoIP PECL extension
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
Add
in php.ini extension=geoip.so
Then just restart php (in the case of nginx+php, but apache+php does not need to be restarted)
Now, you can use some of the GeoIP functions in the php manual
http://cn. php.net/manual/en/book.geoip.php

Reference: http://blog.csdn.net/prince2270/article/details/4592753

The above introduces the geoip+php example: obtaining the country name and code through IP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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