PHP获取IP及地区信息(纯真IP数据库)

  昨天在写程序的时候,发现在用户的时候记录IP和地区信息也许以后用得上,去网上找了找,发现实现的方式有好多好多,因为我用的ThinkPHP,后来又去TP官网找了找,最后采用了下面这种方法。

  1 <?php
  2 // +----------------------------------------------------------------------
  3 // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4 // +----------------------------------------------------------------------
  5 // | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
  6 // +----------------------------------------------------------------------
  7 // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8 // +----------------------------------------------------------------------
  9 // | Author: liu21st <liu21st@gmail.com>
 10 // +----------------------------------------------------------------------
 11 
 12 /**
 13  * IP 地理位置查询类 修改自 CoolCode.CN
 14  * 由于使用UTF8编码 如果使用纯真IP地址库的话 需要对返回结果进行编码转换
 15  * @author liu21st <liu21st@gmail.com>
 16  */
 17 class IpLocation {
 18     /**
 19      * QQWry.Dat文件指针
 20      *
 21      * @var resource
 22      */
 23     private $fp;
 24 
 25     /**
 26      * 第一条IP记录的偏移地址
 27      *
 28      * @var int
 29      */
 30     private $firstip;
 31 
 32     /**
 33      * 最后一条IP记录的偏移地址
 34      *
 35      * @var int
 36      */
 37     private $lastip;
 38 
 39     /**
 40      * IP记录的总条数(不包含版本信息记录)
 41      *
 42      * @var int
 43      */
 44     private $totalip;
 45 
 46     /**
 47      * 构造函数,打开 QQWry.Dat 文件并初始化类中的信息
 48      *
 49      * @param string $filename
 50      * @return IpLocation
 51      */
 52     public function __construct($filename = "UTFWry.dat") {
 53         $this->fp = 0;
 54         if (($this->fp = fopen(dirname(__FILE__).'/'.$filename, 'rb')) !== false) {
 55             $this->firstip = $this->getlong();
 56             $this->lastip = $this->getlong();
 57             $this->totalip = ($this->lastip - $this->firstip) / 7;
 58         }
 59     }
 60 
 61     /**
 62      * 返回读取的长整型数
 63      *
 64      * @access private
 65      * @return int
 66      */
 67     private function getlong() {
 68         //将读取的little-endian编码的4个字节转化为长整型数
 69         $result = unpack('Vlong', fread($this->fp, 4));
 70         return $result['long'];
 71     }
 72 
 73     /**
 74      * 返回读取的3个字节的长整型数
 75      *
 76      * @access private
 77      * @return int
 78      */
 79     private function getlong3() {
 80         //将读取的little-endian编码的3个字节转化为长整型数
 81         $result = unpack('Vlong', fread($this->fp, 3).chr(0));
 82         return $result['long'];
 83     }
 84 
 85     /**
 86      * 返回压缩后可进行比较的IP地址
 87      *
 88      * @access private
 89      * @param string $ip
 90      * @return string
 91      */
 92     private function packip($ip) {
 93         // 将IP地址转化为长整型数,如果在PHP5中,IP地址错误,则返回False,
 94         // 这时intval将Flase转化为整数-1,之后压缩成big-endian编码的字符串
 95         return pack('N', intval(ip2long($ip)));
 96     }
 97 
 98     /**
 99      * 返回读取的字符串
100      *
101      * @access private
102      * @param string $data
103      * @return string
104      */
105     private function getstring($data = "") {
106         $char = fread($this->fp, 1);
107         while (ord($char) > 0) { // 字符串按照C格式保存,以\0结束
108             $data .= $char; // 将读取的字符连接到给定字符串之后
109             $char = fread($this->fp, 1);
110         }
111         return $data;
112 //        return iconv('gb2312', 'utf-8', $data);    //通用函数,不能在这转
113     }
114 
115     /**
116      * 返回地区信息
117      *
118      * @access private
119      * @return string
120      */
121     private function getarea() {
122         $byte = fread($this->fp, 1); // 标志字节
123         switch (ord($byte)) {
124             case 0: // 没有区域信息
125                 $area = "";
126                 break;
127             case 1:
128             case 2: // 标志字节为1或2,表示区域信息被重定向
129                 fseek($this->fp, $this->getlong3());
130                 $area = $this->getstring();
131                 break;
132             default: // 否则,表示区域信息没有被重定向
133                 $area = $this->getstring($byte);
134                 break;
135         }
136         return $area;
137 //        return iconv('gb2312', 'utf-8', $area);    //在最后统一转
138     }
139 
140     /**
141      * 根据所给 IP 地址或域名返回所在地区信息
142      *
143      * @access public
144      * @param string $ip
145      * @return array
146      */
147     public function getlocation($ip='') {
148         if (!$this->fp) return null; // 如果数据文件没有被正确打开,则直接返回空
149         if(empty($ip)) $ip = get_client_ip();
150         $location['ip'] = gethostbyname($ip); // 将输入的域名转化为IP地址
151         $ip = $this->packip($location['ip']); // 将输入的IP地址转化为可比较的IP地址
152         // 不合法的IP地址会被转化为255.255.255.255
153         // 对分搜索
154         $l = 0; // 搜索的下边界
155         $u = $this->totalip; // 搜索的上边界
156         $findip = $this->lastip; // 如果没有找到就返回最后一条IP记录(QQWry.Dat的版本信息)
157         while ($l <= $u) { // 当上边界小于下边界时,查找失败
158             $i = floor(($l + $u) / 2); // 计算近似中间记录
159             fseek($this->fp, $this->firstip + $i * 7);
160             $beginip = strrev(fread($this->fp, 4)); // 获取中间记录的开始IP地址
161             // strrev函数在这里的作用是将little-endian的压缩IP地址转化为big-endian的格式
162             // 以便用于比较,后面相同。
163             if ($ip < $beginip) { // 用户的IP小于中间记录的开始IP地址时
164                 $u = $i - 1; // 将搜索的上边界修改为中间记录减一
165             }
166             else {
167                 fseek($this->fp, $this->getlong3());
168                 $endip = strrev(fread($this->fp, 4)); // 获取中间记录的结束IP地址
169                 if ($ip > $endip) { // 用户的IP大于中间记录的结束IP地址时
170                     $l = $i + 1; // 将搜索的下边界修改为中间记录加一
171                 }
172                 else { // 用户的IP在中间记录的IP范围内时
173                     $findip = $this->firstip + $i * 7;
174                     break; // 则表示找到结果,退出循环
175                 }
176             }
177         }
178 
179         //获取查找到的IP地理位置信息
180         fseek($this->fp, $findip);
181         $location['beginip'] = long2ip($this->getlong()); // 用户IP所在范围的开始地址
182         $offset = $this->getlong3();
183         fseek($this->fp, $offset);
184         $location['endip'] = long2ip($this->getlong()); // 用户IP所在范围的结束地址
185         $byte = fread($this->fp, 1); // 标志字节
186         switch (ord($byte)) {
187             case 1: // 标志字节为1,表示国家和区域信息都被同时重定向
188                 $countryOffset = $this->getlong3(); // 重定向地址
189                 fseek($this->fp, $countryOffset);
190                 $byte = fread($this->fp, 1); // 标志字节
191                 switch (ord($byte)) {
192                     case 2: // 标志字节为2,表示国家信息又被重定向
193                         fseek($this->fp, $this->getlong3());
194                         $location['country'] = $this->getstring();
195                         fseek($this->fp, $countryOffset + 4);
196                         $location['area'] = $this->getarea();
197                         break;
198                     default: // 否则,表示国家信息没有被重定向
199                         $location['country'] = $this->getstring($byte);
200                         $location['area'] = $this->getarea();
201                         break;
202                 }
203                 break;
204             case 2: // 标志字节为2,表示国家信息被重定向
205                 fseek($this->fp, $this->getlong3());
206                 $location['country'] = $this->getstring();
207                 fseek($this->fp, $offset + 8);
208                 $location['area'] = $this->getarea();
209                 break;
210             default: // 否则,表示国家信息没有被重定向
211                 $location['country'] = $this->getstring($byte);
212                 $location['area'] = $this->getarea();
213                 break;
214         }
215         if (trim($location['country']) == 'CZ88.NET') { // CZ88.NET表示没有有效信息
216             $location['country'] = '未知';
217         }
218         if (trim($location['area']) == 'CZ88.NET') {
219             $location['area'] = '';
220         }
221 
222         $location['country']=iconv('gb2312', 'utf-8', $location['country']);
223         $location['area']=iconv('gb2312', 'utf-8', $location['area']);
224 
225         return $location;
226     }
227 
228     /**
229      * 析构函数,用于在页面执行结束后自动关闭打开的文件。
230      *
231      */
232     public function __destruct() {
233         if ($this->fp) {
234             fclose($this->fp);
235         }
236         $this->fp = 0;
237     }
238 
239 }
IpLocation.class.php

  

  这个是TP里带的,从上面的信息上来看已经很旧了,不过感觉写的还不错,就没改什么,只是在后面加上了

$location['country']=iconv('gb2312', 'utf-8', $location['country']);
$location['area']=iconv('gb2312', 'utf-8', $location['area']);

  

  因为TP的纯真数据库已经转码了,但是很旧,似乎还是2012年的,IP这东西,那么老的东西估计很不准,于是我去纯真官网下了一个,但是纯真本身是GB2312的,所以要加上上面这两句转码一下。
然后在项目中导入了这个PHP类以后,这样去用就可以。

$ip=get_client_ip();
$ipData=new IpLocation("QQWry20140125.dat");
$ipInfo=$ipData->getlocation($ip);

  

  得到的结果是这样的,测试IP:218.197.147.154。

array (size=5)
  'ip' => string '218.197.147.154' (length=15)
  'beginip' => string '218.197.146.1' (length=13)
  'endip' => string '218.197.147.154' (length=15)
  'country' => string '湖北省武汉大学' (length=21)
  'area' => string '外语自主学习中心' (length=24)

  

  最新版的纯真数据库去纯真官网下就可以,里面的QQWry.dat就是,用的时候也可以像我那样在后面标上版本,免得以后记不清。然后把.dat跟上面的php类放在一个目录下就OK啦。

posted @ 2014-02-06 11:21  forDawn  阅读(4747)  评论(0编辑  收藏  举报