Using GeoIP with PHP - Part 3

Continue from part 3. We will try another approach using plain PHP library file instead of apt-get or pecl as shown in Part 1 and 2. This method is suitable if you don’t have full or root access to your machine. Example is using shared hosting.

Clone the geoip api library.
$ git clone

Try run one of example script.
$ cd geoip-api-php
$ php -f sample_city.php
PHP Fatal error:  Cannot redeclare geoip_country_code_by_name() in /home/kianmeng/project/geoip-api-php/ on line 439

Yup, method name conflict. In PHP, all methods are in global namespace, hence the name collision. Which is why they introduce ugly-hack of namespace in PHP to solve this problem. We have to remove our PECL-installed geoip extension in Part 2.
$ sudo pecl uninstall geoip
$ sudo rm -rf /etc/php5/conf.d/geoip.ini

Download and uncompress the sample data file.
$ wget
$ gunzip GeoIP.dat.gz

Create this sample test code (test_geoip.php).
require_once "";

$gi = geoip_open("GeoIP.dat", GEOIP_STANDARD);
echo geoip_country_code_by_name($gi, ""), "\n";

Run the script.
$ php -f test_geoip.php

Another similar sample test code (test_cached_geoip.php) but using memory caching.
require_once "";

$gi = geoip_open("GeoIP.dat", GEOIP_SHARED_MEMORY);
echo geoip_country_code_by_name($gi, ""), "\n";

Both the geoip extension and geoip library cannot be used interchangeably. The extension is newer and more update-to-date. If you need a quick IP-to-country lookup but no root access to your machine, just use the library.

No comments:

Post a Comment