Skip to content

Instantly share code, notes, and snippets.

@PsyChip
Created August 23, 2015 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PsyChip/8a668bf0478db9790382 to your computer and use it in GitHub Desktop.
Save PsyChip/8a668bf0478db9790382 to your computer and use it in GitHub Desktop.
Cross-version library for maxmind offline geolocation api. download depencies and databases from https://www.maxmind.com
<?php
# Maxmind Geolocation Database
# Portable library for cross-version readings
#
# Armagan Corlu aka Psy_Chip
# root@psychip.net
# 30.08.2014
#
# sample usage:
# $obj = new maxgeolocation(2); // <=== select db version 1 or 2
# $obj->geoinfo('127.0.0.1'); // returns an array with country & city information
$root = dirname(__FILE__);
require_once $root . '/GeoliteV2/Reader.php';
require_once $root . '/GeoliteV2/Reader/Util.php';
require_once $root . '/GeoliteV2/Reader/Decoder.php';
require_once $root . '/GeoliteV2/Reader/InvalidDatabaseException.php';
require_once $root . '/GeoliteV2/Reader/Metadata.php';
use MaxMind\Db\Reader;
unset($root);
class maxgeolocation {
var $dbv1 = "Geolite/db/GeoIPCity_08_2012.dat";
var $dbv2 = "GeoliteV2/db/GeoLite2-City.mmdb";
private $root;
private $db;
private $ver;
function __construct($version = 2) {
$this->root = dirname(__FILE__);
switch ($version) {
case 1:
$this->db = $this->root . DIRECTORY_SEPARATOR . $this->dbv1;
include_once $this->root . "/Geolite/geoipcity.inc";
break;
case 2:
$this->db = $this->dbv2;
break;
}
$this->ver = $version;
}
private function obj2array($data) {
if (is_array($data) || is_object($data)) {
$result = [];
foreach ($data as $key => $value) {
$result[$key] = $this->obj2array($value);
}
return $result;
}
return $data;
}
private function geoinfo_ipv1($ip) {
$gi = geoip_open($this->db, GEOIP_STANDARD);
$record = geoip_record_by_addr($gi, $ip);
geoip_close($gi);
return $this->obj2array($record);
}
private function geoinfo_ipv2($ip) {
$reader = new Reader($this->db);
$record = $reader->get($ip);
$tmp = $this->obj2array($record);
$data = [];
$data['country_code'] = $tmp['country']['iso_code'];
$data['country_name'] = $tmp['country']['names']['en'];
$data['city'] = $tmp['city']['names']['en'];
$data['latitude'] = $tmp['location']['latitude'];
$data['longitude'] = $tmp['location']['longitude'];
return $data;
}
public function geoinfo($ip) {
switch ($this->ver) {
case 1:
return $this->geoinfo_ipv1($ip);
case 2:
return $this->geoinfo_ipv2($ip);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment