Home  >  Article  >  Backend Development  >  php GeoIP library usage tutorial example

php GeoIP library usage tutorial example

WBOY
WBOYOriginal
2016-07-25 09:11:561266browse

php GeoIP library usage tutorial

What is GepIP? The so-called GeoIP is to use the visitor's IP to locate his latitude and longitude, country/region, province, city, and even street location information. The technology here is not a difficult problem, the key lies in having an accurate database. With accurate data sources, you can earn a little money with rare goods, but what we pursue is to promote the spirit of cooperation and collective contribution for everyone to enjoy.

How to use GeoIP? First we need data information, so we first obtain a free database: GeoIP.dat.gz, and then decompress it to get: GeoIP.dat. Then we perform on-demand operations on the data files. The example here uses PHP. GeoIP + PHP usage

Method 1: Download the GeoIP PHP file geoip.inc. Download package

  1. include("geoip.inc.php");
  2. // Open the data file
  3. $gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
  4. // Get the country code
  5. $country_code = geoip_country_code_by_addr( $gi, $_SERVER['REMOTE_ADDR']);
  6. echo "Your country code is: $country_code ";
  7. // Get the country name
  8. $country_name = geoip_country_name_by_addr($gi, $_SERVER['REMOTE_ADDR']);
  9. echo "Your country name is: $country_name ";
  10. //Close the file
  11. geoip_close($gi);
Copy code

Note: If you test locally, because $_SERVER['REMOTE_ADDR'] and $_SERVER['REMOTE_ADDR '] may be 127.0.0.1, so the output content is empty. You can bring your own IP for testing

Method 2: Install GeoIP as a PHP extension

  1. yum install GeoIP GeoIP-data GeoIP-devel
Copy code

Download GeoIP database

  1. wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
  2. gzip -d GeoLiteCity.dat.gz
  3. mv GeoLiteCity.dat /var/lib/GeoIP/GeoIPCity .dat
Copy code

Download GeoIP’s PECL extension Download address http://pecl.php.net/package/geoip

  1. wget -c http://pecl.php.net/get/geoip-1.0.7.tgz
  2. tar -zxvf geoip-1.0.7.tgz
Copy the code

Install GeoIP PECL extension

  1. cd geoip-1.0.7
  2. /usr/local/php/bin/phpize
  3. ./configure --with-php-config=/usr/local/php/bin/php-config --with -geoip
  4. make
  5. make install
Copy the code

and add it to php.ini extension=geoip.so Then just restart php.

Then, you can use some of the GeoIP functions in the php manual.



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