Ip2Region.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <?php
  2. /**
  3. * ip2region php seacher client class
  4. * @author chenxin<chenxin619315@gmail.com>
  5. * @date 2015-10-29
  6. */
  7. defined('INDEX_BLOCK_LENGTH') or define('INDEX_BLOCK_LENGTH', 12);
  8. defined('TOTAL_HEADER_LENGTH') or define('TOTAL_HEADER_LENGTH', 8192);
  9. class Ip2Region
  10. {
  11. /**
  12. * db file handler
  13. */
  14. private $dbFileHandler = null;
  15. /**
  16. * header block info
  17. */
  18. private $HeaderSip = null;
  19. private $HeaderPtr = null;
  20. private $headerLen = 0;
  21. /**
  22. * super block index info
  23. */
  24. private $firstIndexPtr = 0;
  25. private $lastIndexPtr = 0;
  26. private $totalBlocks = 0;
  27. /**
  28. * for memory mode only
  29. * the original db binary string
  30. */
  31. private $dbBinStr = null;
  32. private $dbFile = null;
  33. /**
  34. * construct method
  35. * @param string $ip2regionFile
  36. */
  37. public function __construct($ip2regionFile = null)
  38. {
  39. $this->dbFile = is_null($ip2regionFile) ? __DIR__ . '/ip2region.db' : $ip2regionFile;
  40. }
  41. /**
  42. * all the db binary string will be loaded into memory
  43. * then search the memory only and this will a lot faster than disk base search
  44. * @Note:
  45. * invoke it once before put it to public invoke could make it thread safe
  46. *
  47. * @param string $ip
  48. * @return array|null
  49. * @throws Exception
  50. */
  51. public function memorySearch($ip)
  52. {
  53. // check and load the binary string for the first time
  54. if ($this->dbBinStr == null) {
  55. $this->dbBinStr = file_get_contents($this->dbFile);
  56. if ($this->dbBinStr == false) {
  57. throw new Exception("Fail to open the db file {$this->dbFile}");
  58. }
  59. $this->firstIndexPtr = self::getLong($this->dbBinStr, 0);
  60. $this->lastIndexPtr = self::getLong($this->dbBinStr, 4);
  61. $this->totalBlocks = ($this->lastIndexPtr - $this->firstIndexPtr) / INDEX_BLOCK_LENGTH + 1;
  62. }
  63. if (is_string($ip)) $ip = self::safeIp2long($ip);
  64. // binary search to define the data
  65. $l = 0;
  66. $h = $this->totalBlocks;
  67. $dataPtr = 0;
  68. while ($l <= $h) {
  69. $m = (($l + $h) >> 1);
  70. $p = $this->firstIndexPtr + $m * INDEX_BLOCK_LENGTH;
  71. $sip = self::getLong($this->dbBinStr, $p);
  72. if ($ip < $sip) {
  73. $h = $m - 1;
  74. } else {
  75. $eip = self::getLong($this->dbBinStr, $p + 4);
  76. if ($ip > $eip) {
  77. $l = $m + 1;
  78. } else {
  79. $dataPtr = self::getLong($this->dbBinStr, $p + 8);
  80. break;
  81. }
  82. }
  83. }
  84. //not matched just stop it here
  85. if ($dataPtr == 0) return null;
  86. //get the data
  87. $dataLen = (($dataPtr >> 24) & 0xFF);
  88. $dataPtr = ($dataPtr & 0x00FFFFFF);
  89. return array(
  90. 'city_id' => self::getLong($this->dbBinStr, $dataPtr),
  91. 'region' => substr($this->dbBinStr, $dataPtr + 4, $dataLen - 4),
  92. );
  93. }
  94. /**
  95. * get the data block through the specified ip address or long ip numeric with binary search algorithm
  96. * @param string ip
  97. * @return array|null Array or NULL for any error
  98. * @throws Exception
  99. */
  100. public function binarySearch($ip)
  101. {
  102. //check and conver the ip address
  103. if (is_string($ip)) $ip = self::safeIp2long($ip);
  104. if ($this->totalBlocks == 0) {
  105. //check and open the original db file
  106. if ($this->dbFileHandler == null) {
  107. $this->dbFileHandler = fopen($this->dbFile, 'r');
  108. if ($this->dbFileHandler == false) {
  109. throw new Exception("Fail to open the db file {$this->dbFile}");
  110. }
  111. }
  112. fseek($this->dbFileHandler, 0);
  113. $superBlock = fread($this->dbFileHandler, 8);
  114. $this->firstIndexPtr = self::getLong($superBlock, 0);
  115. $this->lastIndexPtr = self::getLong($superBlock, 4);
  116. $this->totalBlocks = ($this->lastIndexPtr - $this->firstIndexPtr) / INDEX_BLOCK_LENGTH + 1;
  117. }
  118. //binary search to define the data
  119. $l = 0;
  120. $h = $this->totalBlocks;
  121. $dataPtr = 0;
  122. while ($l <= $h) {
  123. $m = (($l + $h) >> 1);
  124. $p = $m * INDEX_BLOCK_LENGTH;
  125. fseek($this->dbFileHandler, $this->firstIndexPtr + $p);
  126. $buffer = fread($this->dbFileHandler, INDEX_BLOCK_LENGTH);
  127. $sip = self::getLong($buffer, 0);
  128. if ($ip < $sip) {
  129. $h = $m - 1;
  130. } else {
  131. $eip = self::getLong($buffer, 4);
  132. if ($ip > $eip) {
  133. $l = $m + 1;
  134. } else {
  135. $dataPtr = self::getLong($buffer, 8);
  136. break;
  137. }
  138. }
  139. }
  140. // not matched just stop it here
  141. return $this->notMatchedJustStopItHere($dataPtr);
  142. }
  143. /**
  144. * get the data block associated with the specified ip with b-tree search algorithm
  145. * @Note not thread safe
  146. * @param string ip
  147. * @return array|null Array for NULL for any error
  148. * @throws Exception
  149. */
  150. public function btreeSearch($ip)
  151. {
  152. if (is_string($ip)) $ip = self::safeIp2long($ip);
  153. //check and load the header
  154. if ($this->HeaderSip == null) {
  155. //check and open the original db file
  156. if ($this->dbFileHandler == null) {
  157. $this->dbFileHandler = fopen($this->dbFile, 'r');
  158. if ($this->dbFileHandler == false) {
  159. throw new Exception("Fail to open the db file {$this->dbFile}");
  160. }
  161. }
  162. fseek($this->dbFileHandler, 8);
  163. $buffer = fread($this->dbFileHandler, TOTAL_HEADER_LENGTH);
  164. //fill the header
  165. $idx = 0;
  166. $this->HeaderSip = array();
  167. $this->HeaderPtr = array();
  168. for ($i = 0; $i < TOTAL_HEADER_LENGTH; $i += 8) {
  169. $startIp = self::getLong($buffer, $i);
  170. $dataPtr = self::getLong($buffer, $i + 4);
  171. if ($dataPtr == 0) break;
  172. $this->HeaderSip[] = $startIp;
  173. $this->HeaderPtr[] = $dataPtr;
  174. $idx++;
  175. }
  176. $this->headerLen = $idx;
  177. }
  178. //1. define the index block with the binary search
  179. $l = 0;
  180. $h = $this->headerLen;
  181. $sptr = 0;
  182. $eptr = 0;
  183. while ($l <= $h) {
  184. $m = (($l + $h) >> 1);
  185. // perfetc matched, just return it
  186. if ($ip == $this->HeaderSip[$m]) {
  187. if ($m > 0) {
  188. $sptr = $this->HeaderPtr[$m - 1];
  189. $eptr = $this->HeaderPtr[$m];
  190. } else {
  191. $sptr = $this->HeaderPtr[$m];
  192. $eptr = $this->HeaderPtr[$m + 1];
  193. }
  194. break;
  195. }
  196. // less then the middle value
  197. if ($ip < $this->HeaderSip[$m]) {
  198. if ($m == 0) {
  199. $sptr = $this->HeaderPtr[$m];
  200. $eptr = $this->HeaderPtr[$m + 1];
  201. break;
  202. } elseif ($ip > $this->HeaderSip[$m - 1]) {
  203. $sptr = $this->HeaderPtr[$m - 1];
  204. $eptr = $this->HeaderPtr[$m];
  205. break;
  206. }
  207. $h = $m - 1;
  208. } else {
  209. if ($m == $this->headerLen - 1) {
  210. $sptr = $this->HeaderPtr[$m - 1];
  211. $eptr = $this->HeaderPtr[$m];
  212. break;
  213. } elseif ($ip <= $this->HeaderSip[$m + 1]) {
  214. $sptr = $this->HeaderPtr[$m];
  215. $eptr = $this->HeaderPtr[$m + 1];
  216. break;
  217. }
  218. $l = $m + 1;
  219. }
  220. }
  221. //match nothing just stop it
  222. if ($sptr == 0) return null;
  223. //2. search the index blocks to define the data
  224. $blockLen = $eptr - $sptr;
  225. fseek($this->dbFileHandler, $sptr);
  226. $index = fread($this->dbFileHandler, $blockLen + INDEX_BLOCK_LENGTH);
  227. $dataPtr = 0;
  228. $l = 0;
  229. $h = $blockLen / INDEX_BLOCK_LENGTH;
  230. while ($l <= $h) {
  231. $m = (($l + $h) >> 1);
  232. $p = (int)($m * INDEX_BLOCK_LENGTH);
  233. $sip = self::getLong($index, $p);
  234. if ($ip < $sip) {
  235. $h = $m - 1;
  236. } else {
  237. $eip = self::getLong($index, $p + 4);
  238. if ($ip > $eip) {
  239. $l = $m + 1;
  240. } else {
  241. $dataPtr = self::getLong($index, $p + 8);
  242. break;
  243. }
  244. }
  245. }
  246. // not matched
  247. return $this->notMatchedJustStopItHere($dataPtr);
  248. }
  249. /**
  250. * safe self::safeIp2long function
  251. * @param string ip
  252. * */
  253. public static function safeIp2long($ip)
  254. {
  255. $ip = ip2long($ip);
  256. // convert signed int to unsigned int if on 32-bit operating system
  257. if ($ip < 0 && PHP_INT_SIZE == 4) {
  258. $ip = sprintf("%u", $ip);
  259. }
  260. return $ip;
  261. }
  262. /**
  263. * read a long from a byte buffer
  264. * @param mixed b
  265. * @param integer offset
  266. */
  267. public static function getLong($b, $offset)
  268. {
  269. $val = (
  270. (ord($b[$offset++])) |
  271. (ord($b[$offset++]) << 8) |
  272. (ord($b[$offset++]) << 16) |
  273. (ord($b[$offset]) << 24)
  274. );
  275. // convert signed int to unsigned int if on 32-bit operating system
  276. if ($val < 0 && PHP_INT_SIZE == 4) {
  277. $val = sprintf("%u", $val);
  278. }
  279. return $val;
  280. }
  281. /**
  282. * destruct method, resource destroy
  283. */
  284. public function __destruct()
  285. {
  286. if ($this->dbFileHandler != null) {
  287. fclose($this->dbFileHandler);
  288. }
  289. $this->dbBinStr = null;
  290. $this->HeaderSip = null;
  291. $this->HeaderPtr = null;
  292. }
  293. /**
  294. * @param mixed $dataPtr
  295. * @return array|null
  296. */
  297. public function notMatchedJustStopItHere($dataPtr)
  298. {
  299. if ($dataPtr == 0) return null;
  300. // get the data
  301. $dataLen = (($dataPtr >> 24) & 0xFF);
  302. $dataPtr = ($dataPtr & 0x00FFFFFF);
  303. fseek($this->dbFileHandler, $dataPtr);
  304. $data = fread($this->dbFileHandler, $dataLen);
  305. return array(
  306. 'city_id' => self::getLong($data, 0),
  307. 'region' => substr($data, 4),
  308. );
  309. }
  310. /**
  311. * 直接查询并返回名称
  312. * @param string $ip
  313. * @return string
  314. * @throws \Exception
  315. */
  316. public function simple($ip)
  317. {
  318. $geo = $this->memorySearch($ip);
  319. $arr = explode('|', str_replace('0|', '|', isset($geo['region']) ? $geo['region'] : ''));
  320. if (($last = array_pop($arr)) === '内网IP') $last = '';
  321. return join('', $arr) . (empty($last) ? '' : "【{$last}】");
  322. }
  323. }