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 https://github.com/maxmind/geoip-api-php

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/geoip.inc 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 http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
$ gunzip GeoIP.dat.gz

Create this sample test code (test_geoip.php).
<?php
require_once "geoip.inc";

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

Run the script.
$ php -f test_geoip.php
US

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

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

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