Ip2Region.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 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 throught the specifield 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('city_id' => self::getLong($data, 0), 'region' => substr($data, 4));
  151. }
  152. /**
  153. * get the data block associated with the specifield ip with b-tree search algorithm
  154. * @Note: not thread safe
  155. *
  156. * @param string ip
  157. * @return Mixed Array for NULL for any error
  158. * @throws Exception
  159. */
  160. public function btreeSearch($ip)
  161. {
  162. if (is_string($ip)) $ip = self::safeIp2long($ip);
  163. //check and load the header
  164. if ($this->HeaderSip == null) {
  165. //check and open the original db file
  166. if ($this->dbFileHandler == null) {
  167. $this->dbFileHandler = fopen($this->dbFile, 'r');
  168. if ($this->dbFileHandler == false) {
  169. throw new Exception("Fail to open the db file {$this->dbFile}");
  170. }
  171. }
  172. fseek($this->dbFileHandler, 8);
  173. $buffer = fread($this->dbFileHandler, TOTAL_HEADER_LENGTH);
  174. //fill the header
  175. $idx = 0;
  176. $this->HeaderSip = array();
  177. $this->HeaderPtr = array();
  178. for ($i = 0; $i < TOTAL_HEADER_LENGTH; $i += 8) {
  179. $startIp = self::getLong($buffer, $i);
  180. $dataPtr = self::getLong($buffer, $i + 4);
  181. if ($dataPtr == 0) break;
  182. $this->HeaderSip[] = $startIp;
  183. $this->HeaderPtr[] = $dataPtr;
  184. $idx++;
  185. }
  186. $this->headerLen = $idx;
  187. }
  188. //1. define the index block with the binary search
  189. $l = 0;
  190. $h = $this->headerLen;
  191. $sptr = 0;
  192. $eptr = 0;
  193. while ($l <= $h) {
  194. $m = (($l + $h) >> 1);
  195. //perfetc matched, just return it
  196. if ($ip == $this->HeaderSip[$m]) {
  197. if ($m > 0) {
  198. $sptr = $this->HeaderPtr[$m - 1];
  199. $eptr = $this->HeaderPtr[$m];
  200. } else {
  201. $sptr = $this->HeaderPtr[$m];
  202. $eptr = $this->HeaderPtr[$m + 1];
  203. }
  204. break;
  205. }
  206. //less then the middle value
  207. if ($ip < $this->HeaderSip[$m]) {
  208. if ($m == 0) {
  209. $sptr = $this->HeaderPtr[$m];
  210. $eptr = $this->HeaderPtr[$m + 1];
  211. break;
  212. } elseif ($ip > $this->HeaderSip[$m - 1]) {
  213. $sptr = $this->HeaderPtr[$m - 1];
  214. $eptr = $this->HeaderPtr[$m];
  215. break;
  216. }
  217. $h = $m - 1;
  218. } else {
  219. if ($m == $this->headerLen - 1) {
  220. $sptr = $this->HeaderPtr[$m - 1];
  221. $eptr = $this->HeaderPtr[$m];
  222. break;
  223. } elseif ($ip <= $this->HeaderSip[$m + 1]) {
  224. $sptr = $this->HeaderPtr[$m];
  225. $eptr = $this->HeaderPtr[$m + 1];
  226. break;
  227. }
  228. $l = $m + 1;
  229. }
  230. }
  231. //match nothing just stop it
  232. if ($sptr == 0) return null;
  233. //2. search the index blocks to define the data
  234. $blockLen = $eptr - $sptr;
  235. fseek($this->dbFileHandler, $sptr);
  236. $index = fread($this->dbFileHandler, $blockLen + INDEX_BLOCK_LENGTH);
  237. $dataptr = 0;
  238. $l = 0;
  239. $h = $blockLen / INDEX_BLOCK_LENGTH;
  240. while ($l <= $h) {
  241. $m = (($l + $h) >> 1);
  242. $p = (int)($m * INDEX_BLOCK_LENGTH);
  243. $sip = self::getLong($index, $p);
  244. if ($ip < $sip) {
  245. $h = $m - 1;
  246. } else {
  247. $eip = self::getLong($index, $p + 4);
  248. if ($ip > $eip) {
  249. $l = $m + 1;
  250. } else {
  251. $dataptr = self::getLong($index, $p + 8);
  252. break;
  253. }
  254. }
  255. }
  256. //not matched
  257. if ($dataptr == 0) return null;
  258. //3. get the data
  259. $dataLen = (($dataptr >> 24) & 0xFF);
  260. $dataPtr = ($dataptr & 0x00FFFFFF);
  261. fseek($this->dbFileHandler, $dataPtr);
  262. $data = fread($this->dbFileHandler, $dataLen);
  263. return array('city_id' => self::getLong($data, 0), 'region' => substr($data, 4));
  264. }
  265. /**
  266. * safe self::safeIp2long function
  267. *
  268. * @param string ip
  269. * @return string
  270. */
  271. public static function safeIp2long($ip)
  272. {
  273. $ip = ip2long($ip);
  274. // convert signed int to unsigned int if on 32 bit operating system
  275. if ($ip < 0 && PHP_INT_SIZE == 4) {
  276. $ip = sprintf("%u", $ip);
  277. }
  278. return $ip;
  279. }
  280. /**
  281. * read a long from a byte buffer
  282. *
  283. * @param integer b
  284. * @param integer offset
  285. * @return string
  286. */
  287. public static function getLong($b, $offset)
  288. {
  289. $val = (
  290. (ord($b[$offset++])) |
  291. (ord($b[$offset++]) << 8) |
  292. (ord($b[$offset++]) << 16) |
  293. (ord($b[$offset]) << 24)
  294. );
  295. // convert signed int to unsigned int if on 32 bit operating system
  296. if ($val < 0 && PHP_INT_SIZE == 4) {
  297. $val = sprintf("%u", $val);
  298. }
  299. return $val;
  300. }
  301. /**
  302. * destruct method, resource destroy
  303. */
  304. public function __destruct()
  305. {
  306. if ($this->dbFileHandler != null) {
  307. fclose($this->dbFileHandler);
  308. }
  309. $this->dbBinStr = null;
  310. $this->HeaderSip = null;
  311. $this->HeaderPtr = null;
  312. }
  313. }