search
HomeBackend DevelopmentPHP TutorialSimple example of php reading innocent ip database

  1. /*----------------------------------------- ----------
  2. ip2address [qqwry.dat]
  3. --------------------------------- --------------------*/
  4. class ip {
  5. var $fh; //IP database file handle
  6. var $first; //First index
  7. var $last; //The last index
  8. var $total; //Total indexes
  9. //Constructor function
  10. function __construct() {
  11. $this->fh = fopen('qqwry.dat', 'rb'); / /qqwry.dat file
  12. $this->first = $this->getLong4();
  13. $this->last = $this->getLong4();
  14. $this->total = ($this ->last - $this->first) / 7; //Each index is 7 bytes
  15. }
  16. //Check the legality of the IP
  17. function checkIp($ip) {
  18. $arr = explode('.', $ip);
  19. if(count($arr) !=4 ) {
  20. return false;
  21. } else {
  22. for ($i=0; $i if ($arr[$ i] '255') {
  23. return false;
  24. }
  25. }
  26. }
  27. return true;
  28. }
  29. function getLong4() {
  30. //Read little -Convert 4 bytes of endian encoding to long integer
  31. $result = unpack('Vlong', fread($this->fh, 4));
  32. return $result['long'];
  33. }
  34. function getLong3() {
  35. //Read the 3 bytes of little-endian encoding and convert it into a long integer
  36. $result = unpack('Vlong', fread($this->fh, 3).chr(0 ));
  37. return $result['long'];
  38. }
  39. //Query information
  40. function getInfo($data = "") {
  41. $char = fread($this->fh, 1);
  42. while ( ord($char) != 0) { //Country and region information ends with 0
  43. $data .= $char;
  44. $char = fread($this->fh, 1);
  45. }
  46. return $data;
  47. } bbs.it-home.org
  48. //Query area information
  49. function getArea() {
  50. $byte = fread($this->fh, 1); //Flag byte
  51. switch (ord($byte)) {
  52. case 0: $area = ''; break; //There is no area information
  53. case 1: //The area is redirected
  54. fseek($this->fh, $this->getLong3());
  55. $ area = $this->getInfo(); break;
  56. case 2: //Area is redirected
  57. fseek($this->fh, $this->getLong3());
  58. $area = $this- >getInfo(); break;
  59. default: $area = $this->getInfo($byte); break; //The area is not redirected
  60. }
  61. return $area;
  62. }
  63. function ip2addr($ip) {
  64. if(!$this -> checkIp($ip)){
  65. return false;
  66. }
  67. $ip = pack('N', intval(ip2long($ip)));
  68. //Binary search
  69. $ l = 0;
  70. $r = $this->total;
  71. while($l $m = floor(($l + $r) / 2); //Calculate the intermediate index
  72. fseek($this->fh, $this->first + $m * 7);
  73. $beginip = strrev(fread($this->fh, 4)); //The starting IP address of the intermediate index
  74. fseek($this->fh, $this->getLong3());
  75. $endip = strrev(fread($this->fh, 4)); //End IP address of the intermediate index
  76. if ($ ip $r = $m - 1;
  77. } else {
  78. if ($ip > $endip) { //The user's IP is greater than When the ending IP address of the intermediate index is
  79. $l = $m + 1;
  80. } else { //When the user IP is within the IP range of the intermediate index
  81. $findip = $this->first + $m * 7;
  82. break ;
  83. }
  84. }
  85. }
  86. //Query country and region information
  87. fseek($this->fh, $findip);
  88. $location['beginip'] = long2ip($this->getLong4()); / /Start address of the user IP range
  89. $offset = $this->getlong3();
  90. fseek($this->fh, $offset);
  91. $location['endip'] = long2ip($this-> ;getLong4()); //End address of the user IP range
  92. $byte = fread($this->fh, 1); //Flag byte
  93. switch (ord($byte)) {
  94. case 1: //Both country and region information are redirected
  95. $countryOffset = $this->getLong3(); //Redirect address
  96. fseek($this->fh, $countryOffset);
  97. $byte = fread($this ->fh, 1); //Flag byte
  98. switch (ord($byte)) {
  99. case 2: //Country information is redirected twice
  100. fseek($this->fh, $this-> ;getLong3());
  101. $location['country'] = $this->getInfo();
  102. fseek($this->fh, $countryOffset + 4);
  103. $location['area'] = $ this->getArea();
  104. break;
  105. default: //Country information is not redirected twice
  106. $location['country'] = $this->getInfo($byte);
  107. $location['area '] = $this->getArea();
  108. break;
  109. }
  110. break;
  111. case 2: //Country information is redirected
  112. fseek($this->fh, $this->getLong3()) ;
  113. $location['country'] = $this->getInfo();
  114. fseek($this->fh, $offset + 8);
  115. $location['area'] = $this->getArea ();
  116. break;
  117. default: //Country information is not redirected
  118. $location['country'] = $this->getInfo($byte);
  119. $location['area'] = $this-> ;getArea();
  120. break;
  121. }
  122. //gb2312 to utf-8 (remove CZ88.NET displayed when there is no information)
  123. foreach ($location as $k => $v) {
  124. $location[$k] = str_replace('CZ88.NET', '',iconv('gb2312', 'utf-8', $v));
  125. }
  126. return $location;
  127. }
  128. //Destructor
  129. function __destruct() {
  130. fclose($this->fh );
  131. }
  132. }
  133. $ip = new ip();
  134. $addr = $ip -> ip2addr('IP address');
  135. print_r($addr);
  136. ?>
Copy code


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools