Get a localized name of the users city via Maxmind GeoLite2 Free

Moritz picture Moritz · Jan 10, 2014 · Viewed 8.2k times · Source

i want to show the german name of the users city. Is it possible with the free Version of Maxmind Geoip? I did not find a way to open the GeoLite2-City.mmdb or GeoLiteCity.dat, to see which cities are listed, for building my own translation service. How can i open them?

Answer

kitchin picture kitchin · Jan 28, 2014

Here's how to do it without Composer.

Change:

require_once '../vendor/autoload.php';
use MaxMind\Db\Reader;
$reader = new Reader('GeoIP2-City.mmdb');

To:

require_once __DIR__ . '/' . 'Db/Reader.php';
require_once __DIR__ . '/' . 'Db/Reader/Decoder.php';
require_once __DIR__ . '/' . 'Db/Reader/InvalidDatabaseException.php';
require_once __DIR__ . '/' . 'Db/Reader/Metadata.php';
require_once __DIR__ . '/' . 'Db/Reader/Util.php';     // new 2014/09
use MaxMind\Db\Reader;
$mmdb= true ? 'GeoLite2-City.mmdb' : 'GeoLite2-Country.mmdb';
$reader = new Reader( __DIR__  . '/' . $mmdb );

You'll need PHP 5.3+. You even get some savings in code and number of files vs. using Composer. (Some testing code is eliminated, as well as the whole Guzzle structure.) Also, it makes it clearer how namespaces work in PHP as a nice replacement for classes (when classes are used just for name-spacing).

The rest of benchmark.php you can discard and start using $reader->get().

If you do want to benchmark, on most platforms you need to modify the rand() call. Try this:

Change:

$ip = long2ip(rand(0, pow(2, 32) -1));

To:

$n= (float)mt_rand(0, pow(2, 31) - 1);
if (mt_rand(0,1)) $n+= pow(2, 31);
$ip = long2ip($n);

Or just join four mt_rand(0,255)'s with '.', which is probably easier!

........................ Edit 2014/09 ........................

Added 'Db/Reader/Util.php' above.

Version of MaxMind-DB-Reader-php: 1.0.0 (2014-09-22)

Your file structure should look like this:

./benchmark.php
./GeoLite2-City.mmdb
./GeoLite2-Country.mmdb
./Db/Reader.php
./Db/Reader/Decoder.php
./Db/Reader/InvalidDatabaseException.php
./Db/Reader/Metadata.php
./Db/Reader/Util.php