您可以在 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 配置下像这样自动加载它
$autoload['libraries'] = array('CI_GeoIp2'=>'Location');
所以在我使用的脚本中,
$this->Location->getState()
$this->Location->getCity()
... 等等