Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use MaxMind's Databases in php

Tags:

php

geoip

maxmind

I downloaded and extracted GeoLite2-City.mmdb, GeoLite2-Country.mmdb. Both are in htdocs\geoip\

Then, I ran this script. Trouble is, how does this thing work? What is require_once 'vendor/autoload.php'; supposed to contain? Am I missing anything here. I used to use the older versions of these that came as .dat file, and had no problem with them. These .mmdb ones are a little hard for me to crack. All I'm trying to do is get the Country Code, Country Name and other data to store in a db when a user uses the search tool on a page. How do I get this going?

My test page taken from the site

<?php
require_once 'vendor/autoload.php'; //What is this supposed to contain?
use GeoIp2\Database\Reader; // What is this too?

// This creates the Reader object, which should be reused across
// lookups.
$reader = new Reader($_SERVER['DOCUMENT_ROOT'].'\geoip\GeoIP2-City.mmdb'); // Where my DB resides

// Replace "city" with the appropriate method for your database, e.g.,
// "country".
$record = $reader->city('128.101.101.101');

print($record->country->isoCode . "\n"); // 'US'
print($record->country->name . "\n"); // 'United States'
print($record->country->names['zh-CN'] . "\n"); // '??'

print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'

print($record->city->name . "\n"); // 'Minneapolis'

print($record->postal->code . "\n"); // '55455'

print($record->location->latitude . "\n"); // 44.9733
print($record->location->longitude . "\n"); // -93.2323

?>
like image 896
Norman Avatar asked Oct 21 '22 18:10

Norman


1 Answers

I would recommend using the PHP Extension API if you are concerned at all about performance. You can get upwards of 7 million queries per second with the PHP (C API) extension vs 9,000 qps with the pure PHP API.

I describe how to compile the extension, and how to use the mmdb databases in PHP here:

Intro to Maxmind GeoLite2 with Kohana PHP

Geolocate IP Address

like image 120
Jamie Avatar answered Oct 23 '22 13:10

Jamie