CI的model
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Baseip extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('function_lib');
}
function demo(){
$ip = '58.244.191.119';
$city = $this->function_lib->convertip($ip);
$city = iconv('gbk', 'utf-8', $city); //将结果进行转码,如果字符集正确无需转码
print_r($city);
}
}
library下的_lib文件
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Function_lib {
var $CI;
function __construct() {
if (!isset($this->CI)) {
$this->CI = & get_instance();
}
}
function convertip($ip) {
$return = '';
if(preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip)) {
$iparray = explode('.', $ip);
// print_r($ip);exit;
if($iparray[0] == 10 || $iparray[0] == 127 || ($iparray[0] == 192 && $iparray[1] == 168) || ($iparray[0] == 172 && ($iparray[1] >= 16 && $iparray[1] <= 31))) {
$return = '- LAN';
} elseif($iparray[0] > 255 || $iparray[1] > 255 || $iparray[2] > 255 || $iparray[3] > 255) {
$return = '- Invalid IP Address';
} else {
$tinyipfile = "./data/ipdata/tinyipdata.dat";//注意路径
// echo "111";
if(file_exists($tinyipfile)) {
$return = $this->convertip_tiny($ip, $tinyipfile);
// print_r($ip);exit;
}else{
echo "不存在";
}
}
}
return $return;
}
function convertip_tiny($ip, $ipdatafile) {
static $fp = NULL, $offset = array(), $index = NULL;
$ipdot = explode('.', $ip);
$ip = pack('N', ip2long($ip));
$ipdot[0] = (int)$ipdot[0];
$ipdot[1] = (int)$ipdot[1];
if($fp === NULL && $fp = fopen($ipdatafile, 'rb')) {
$offset = unpack('Nlen', fread($fp, 4));
$index = fread($fp, $offset['len'] - 4);
} elseif($fp == FALSE) {
return '- Invalid IP data file';
}
$length = $offset['len'] - 1028;
$start = unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]);
for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8) {
if ($index{$start} . $index{$start + 1} . $index{$start + 2} . $index{$start + 3} >= $ip) {
$index_offset = unpack('Vlen', $index{$start + 4} . $index{$start + 5} . $index{$start + 6} . "\x0");
$index_length = unpack('Clen', $index{$start + 7});
break;
}
}
fseek($fp, $offset['len'] + $index_offset['len'] - 1024);
if($index_length['len']) {
return fread($fp, $index_length['len']);
} else {
return '- Unknown';
}
}
}