Ip2Region.php 11 KB

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