geoip+php Example: Obtaining a country name and code via IP

Source: Internet
Author: User
Tags geoip geoip database php example

GeoIP + PHP Usage

Method One:

Download GeoIP PHP file, save as


PHP uses code

<?phpinclude (""); $gi = Geoip_open ("GeoIP.dat", Geoip_standard); $country _code = Geoip_country_code_ By_addr ($gi, $_server[' remote_addr '); $country _name = Geoip_country_name_by_addr ($gi, $_server[' remote_addr ']); Geoip_close ($gi); $jsonEcho = Array (); $jsonEcho ["error"] = 0; $jsonEcho ["country_code"] = $country _code; $jsonEcho [" Country_name "] = $country _name;function jsonp ($object, $callback = ' callback ') {if (!empty ($_get[$callback])) {Header (' Content-type:application/x-javascript ');} else {header (' Content-type:application/json ');} Return $_get[$callback]. ' ('. Json_encode ($object). ') ';} echo Jsonp ($jsonEcho);? >

Note: If you test locally because $_server[' remote_addr ' and $_server[' REMOTE_ADDR '] may be, the output content is empty. Can bring in the IP test yourself

Method Two:

Installing GeoIP into PHP extensions
Yum Install GeoIP Geoip-data geoip-devel

Download GeoIP Database
Gzip-d GeoLiteCity.dat.gz
MV Geolitecity.dat/var/lib/geoip/geoipcity.dat

Download GeoIP PECL Extension
TAR-ZXVF geoip-1.0.7.tgz

Installing the GeoIP PECL extension
CD geoip-1.0.7
Make install

Add in the php.ini.

Then restart PHP (nginx+php, and apache+php will not have to restart)
Now, you can use the GeoIP partial function in the PHP manual.


geoip+php Example: Obtaining a country name and code via IP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.