これを CodeIgniter 内に埋め込む方法はいくつかあります。
まず、スクリプト内に含める必要があります。
require_once( 'GeoIp2/vendor/autoload.php' );
use GeoIp2\Database\Reader;
Reader()
次に、検出方法を呼び出します
$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;
これを CodeIgniter 3x でテストしたところ、動作しました。
ブリッジクラスを使用しました。/application/libraries
というファイルを作成し、CI_GeoIp2.php
次のコードを追加します。
<?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;
}
}
これで、次を使用してオートロードまたはロードすることができます
$this->load->library("CI_GeoIp2");
autoload.php configの下でこのように自動ロードすることを好みます
$autoload['libraries'] = array('CI_GeoIp2'=>'Location');
したがって、私が使用するスクリプト内では、
$this->Location->getState()
$this->Location->getCity()
... 等々