Few ways you can embed this within CodeIgniter.
First, you need to include it within the script:
require_once( 'GeoIp2/vendor/autoload.php' );
use GeoIp2\Database\Reader;
Next, I call Reader()
for the detection methods
$reader = new Reader('GeoIp2/GeoIP2-City.mmdb');
$record = $reader->city($ip);
// Country (code)
$record->country->isoCode;
// State
$record->mostSpecificSubdivision->name;
// City
$record->city->name;
// zip code
$record->postal->code;
I just tested this on CodeIgniter 3x and works.
I used a bridge class. Inside /application/libraries
create a file called CI_GeoIp2.php
and add the following code.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* GeoIp2 Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category GeoIp2
* @author Timothy Marois <timothymarois@gmail.com>
*/
require_once( APPPATH . 'third_party/GeoIp2/vendor/autoload.php' );
use GeoIp2\Database\Reader;
class CI_GeoIp2 {
protected $record;
protected $database_path = 'third_party/GeoIp2/GeoIP2-City.mmdb';
public function __construct() {
$ci =& get_instance();
$reader = new Reader(APPPATH.$this->database_path);
$ip = $ci->input->ip_address();
if ($ci->input->valid_ip($ip)) {
$this->record = $reader->city($ip);
}
log_message('debug', "CI_GeoIp2 Class Initialized");
}
/**
* getState()
* @return state
*/
public function getState() {
return $this->record->mostSpecificSubdivision->name;;
}
/**
* getState()
* @return country code "US/CA etc"
*/
public function getCountryCode() {
return $this->record->country->isoCode;
}
/**
* getCity()
* @return city name
*/
public function getCity() {
return $this->record->city->name;
}
/**
* getZipCode()
* @return Zip Code (#)
*/
public function getZipCode() {
return $this->record->postal->code;
}
/**
* getRawRecord()
* (if you want to manually extract objects)
*
* @return object of all items
*/
public function getRawRecord() {
return $this->record;
}
}
Now you can either autoload or load it up using
$this->load->library("CI_GeoIp2");
I prefer to autoload it like this under autoload.php config
$autoload['libraries'] = array('CI_GeoIp2'=>'Location');
So within the script I use,
$this->Location->getState()
$this->Location->getCity()
... and so on