Tutorial on using PHP GeoIP

  • 2020-03-31 21:34:43
  • OfStack

GeoIP:
What is GepIP?
The so-called GeoIP is to use the IP of the visitor to locate his latitude and longitude, country/region, province, even the street and other location information. The technology here is not a problem, the key is to have an accurate database. With the accurate data source can make a small amount of money, but carry forward the spirit of cooperation, collective contribution to the public is our pursuit.
How is GeoIP used?
First we need the data information, so get a free database: geoip.dat.gz, then unzip it to get geoip.dat, and then do the data file as needed, using PHP in this example.
The use of GeoIP + PHP
Method one:
Download the GeoIP PHP file geoip.inc. (link: http://xiazai.jb51.net/201103/other/GeoIPdat.rar)
 
include("geoip.inc.php"); 
//Open data file
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD); 
//Get the country code
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']); 
echo "Your country code is: $country_code "; 
//Get the country name
$country_name = geoip_country_name_by_addr($gi, $_SERVER['REMOTE_ADDR']); 
echo "Your country name is: $country_name "; 
//Close the file
geoip_close($gi); 

Note: when tested locally, $_SERVER['REMOTE_ADDR'] and $_SERVER['REMOTE_ADDR'] may be 127.0.0.1 and the output is empty. You can bring in your own IP tests

Method 2:
Install GeoIP as a PHP extension
Yum install GeoIP geoip-data geoip-devel

Download the GeoIP database
Wget HTTP: / / 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
The tar ZXVF - geoip - 1.0.7. TGZ

Install the PECL extension for GeoIP
CD geoip - 1.0.7
/ usr/local/PHP/bin/phpize
. / configure -- with PHP - config = / usr/local/PHP/bin/PHP - config - with - geoip
The make
Make install

Add it to php.ini
The extension = geoip. So
Just restart PHP
Now you can use the GeoIP partial function in the PHP manual

Related articles: