search
HomeBackend DevelopmentPHP TutorialProvide an IP geographical location query class again

IP geographical location query class
  1. /**
  2. File name: IpLocation.class.php
  3. * IP geographical location query class (I uploaded the main file and a test file. There is also QQWry.Dat, which you can download from the Innocence IP library because there is It’s over 6M so I won’t upload it here)
  4. *
  5. * @author Ma Bingyao
  6. * @version 1.5
  7. * @copyright 2005 CoolCode.CN
  8. */
  9. class IpLocation {
  10. /**
  11. * QQWry.Dat file pointer
  12. * @var resource
  13. */
  14. var $fp;
  15. /**
  16. * Offset address of the first IP record
  17. * @var int
  18. */
  19. var $firstip ;
  20. /**
  21. * Offset address of the last IP record
  22. * @var int
  23. */
  24. var $lastip;
  25. /**
  26. * Total number of IP records (excluding version information records)
  27. * @var int
  28. */
  29. var $totalip;
  30. /**
  31. * Constructor, open the QQWry.Dat file and initialize the information in the class
  32. * @param string $filename
  33. * @return IpLocation
  34. */
  35. function __construct($filename = "QQWry .Dat") {
  36. $this->fp = 0;
  37. if (($this->fp = @fopen($filename, 'rb')) !== false) {
  38. $this->firstip = $this->getlong();
  39. $this->lastip = $this->getlong();
  40. $this->totalip = ($this->lastip - $this->firstip) / 7;
  41. //Register the destructor so that it is executed at the end of program execution
  42. register_shutdown_function(array(&$this, '__construct'));
  43. }
  44. }
  45. /**
  46. * Return the read long integer
  47. * @access private
  48. * @return int
  49. */
  50. function getlong() {
  51. //Convert the read 4 bytes of little-endian encoding into a long integer
  52. $result = unpack('Vlong', fread($this->fp, 4));
  53. return $result['long'];
  54. }
  55. /**
  56. * Returns the read 3-byte long integer
  57. *
  58. * @access private
  59. * @return int
  60. */
  61. function getlong3() {
  62. //Convert the read 3 bytes of little-endian encoding into a long integer
  63. $result = unpack('Vlong', fread($this->fp, 3).chr(0));
  64. return $result['long'];
  65. }
  66. /**
  67. * Returns the compressed IP address that can be compared
  68. *
  69. * @access private
  70. * @param string $ip
  71. * @return string
  72. */
  73. function packip($ip) {
  74. // Convert the IP address into a long integer. If the IP address is wrong in PHP5, False will be returned.
  75. // At this time, intval will convert the Flese into an integer -1, and then compress it into big-endian encoded string
  76. return pack('N', intval(ip2long($ip)));
  77. }
  78. /**
  79. * Return the read string
  80. *
  81. * @access private
  82. * @param string $data
  83. * @return string
  84. */
  85. function getstring($data = "") {
  86. $ char = fread($this->fp, 1);
  87. while (ord($char) > 0) { // The string is saved in C format, in
  88. if ($ip $u = $i - 1; // Modify the upper boundary of the search to the intermediate record minus one
  89. } else {
  90. fseek($this->fp, $this->getlong3());
  91. $endip = strrev(fread($this->fp, 4)); // Get the end IP address of the intermediate record
  92. if ($ip > $endip) { // When the user's IP is greater than the end IP address of the intermediate record
  93. $l = $i + 1; // Modify the lower boundary of the search to the intermediate record plus one
  94. } else { // When the user's IP is within the IP range of the intermediate record
  95. $findip = $this->firstip + $i * 7;
  96. break; // It means the result is found and the loop is exited
  97. }
  98. }
  99. }
  100. //Get The IP geographical location information found
  101. fseek($this->fp, $findip);
  102. $location['beginip'] = long2ip($this->getlong()); // The beginning of the range where the user IP is located Address
  103. $offset = $this->getlong3();
  104. fseek($this->fp, $offset);
  105. $location['endip'] = long2ip($this->getlong()); / / End address of the user IP range
  106. $byte = fread($this->fp, 1); // Flag byte
  107. switch (ord($byte)) {
  108. case 1: // Flag byte is 1 , indicating that both country and regional information are redirected at the same time
  109. $countryOffset = $this->getlong3(); // Redirect address
  110. fseek($this->fp, $countryOffset);
  111. $byte = fread($ this->fp, 1); // Flag byte
  112. switch (ord($byte)) {
  113. case 2: // Flag byte is 2, indicating that the country information has been redirected again
  114. fseek($this-> ;fp, $this->getlong3());
  115. $location['country'] = $this->getstring();
  116. fseek($this->fp, $countryOffset + 4);
  117. $location ['area'] = $this->getarea();
  118. break;
  119. default: // Otherwise, it means that the country information is not redirected
  120. $location['country'] = $this->getstring($byte );
  121. $location['area'] = $this->getarea();
  122. break;
  123. }
  124. break;
  125. case 2: // The flag byte is 2, indicating that the country information is redirected
  126. fseek($ this->fp, $this->getlong3());
  127. $location['country'] = $this->getstring();
  128. fseek($this->fp, $offset + 8);
  129. $location['area'] = $this->getarea();
  130. break;
  131. default: // Otherwise, it means that the country information is not redirected
  132. $location['country'] = $this->getstring ($byte);
  133. $location['area'] = $this->getarea();
  134. break;
  135. }
  136. if ($location['country'] == " CZ88.NET") { // CZ88 .NET indicates that there is no valid information
  137. $location['country'] = "Unknown";
  138. }
  139. if ($location['area'] == " CZ88.NET") {
  140. $location['area'] = " ";
  141. }
  142. return $location;
  143. }
  144. /**
  145. * Destructor, used to automatically close the open file after the page execution ends.
  146. *
  147. */
  148. function __desctruct() {
  149. if ($this->fp) {
  150. fclose($this->fp);
  151. }
  152. $this->fp = 0;
  153. }
  154. }
  155. ?>
Copy code
  1. require_once('IpLocation.class.php');
  2. $ip='127.0.0.1';
  3. $idADDR=new IpLocation();
  4. print_r($idADDR->getlocation($ ip));
  5. ?>
Copy code
  1. /**
  2. * IP geographical location query class
  3. *
  4. * @author Ma Bingyao
  5. * @version 1.5
  6. * @copyright 2005 CoolCode.CN
  7. */
  8. class IpLocation {
  9. /**
  10. * QQWry.Dat file pointer
  11. * @var resource
  12. */
  13. var $fp;
  14. /**
  15. * Offset address of the first IP record
  16. * @var int
  17. */
  18. var $firstip ;
  19. /**
  20. * Offset address of the last IP record
  21. * @var int
  22. */
  23. var $lastip;
  24. /**
  25. * Total number of IP records (excluding version information records)
  26. * @var int
  27. */
  28. var $totalip;
  29. /**
  30. * Constructor, open the QQWry.Dat file and initialize the information in the class
  31. * @param string $filename
  32. * @return IpLocation
  33. */
  34. function __construct($filename = "QQWry .Dat") {
  35. $this->fp = 0;
  36. if (($this->fp = @fopen($filename, 'rb')) !== false) {
  37. $this->firstip = $this->getlong();
  38. $this->lastip = $this->getlong();
  39. $this->totalip = ($this->lastip - $this->firstip) / 7;
  40. //Register the destructor so that it is executed at the end of program execution
  41. register_shutdown_function(array(&$this, '__construct'));
  42. }
  43. }
  44. /**
  45. * Return the read long integer
  46. * @access private
  47. * @return int
  48. */
  49. function getlong() {
  50. //Convert the read 4 bytes of little-endian encoding into a long integer
  51. $result = unpack('Vlong', fread($this->fp, 4));
  52. return $result['long'];
  53. }
  54. /**
  55. * Returns the read 3-byte long integer
  56. *
  57. * @access private
  58. * @return int
  59. */
  60. function getlong3() {
  61. //Convert the read 3 bytes of little-endian encoding into a long integer
  62. $result = unpack('Vlong', fread($this->fp, 3).chr(0));
  63. return $result['long'];
  64. }
  65. /**
  66. * Returns the compressed IP address that can be compared
  67. *
  68. * @access private
  69. * @param string $ip
  70. * @return string
  71. */
  72. function packip($ip) {
  73. // Convert the IP address into a long integer. If the IP address is wrong in PHP5, False will be returned.
  74. // At this time, intval will convert the Flese into an integer -1, and then compress it into big-endian encoded string
  75. return pack('N', intval(ip2long($ip)));
  76. }
  77. /**
  78. * Return the read string
  79. *
  80. * @access private
  81. * @param string $data
  82. * @return string
  83. */
  84. function getstring($data = "") {
  85. $ char = fread($this->fp, 1);
  86. while (ord($char) > 0) { // The string is saved in C format, in
  87. if ($ip $u = $i - 1; // Modify the upper boundary of the search to the intermediate record minus one
  88. } else {
  89. fseek($this->fp, $this->getlong3());
  90. $endip = strrev(fread($this->fp, 4)); // Get the end IP address of the intermediate record
  91. if ($ip > $endip) { // When the user's IP is greater than the end IP address of the intermediate record
  92. $l = $i + 1; // Modify the lower boundary of the search to the intermediate record plus one
  93. } else { // When the user's IP is within the IP range of the intermediate record
  94. $findip = $this->firstip + $i * 7;
  95. break; // It means the result is found and the loop is exited
  96. }
  97. }
  98. }
  99. //Get The IP geographical location information found
  100. fseek($this->fp, $findip);
  101. $location['beginip'] = long2ip($this->getlong()); // The beginning of the range where the user IP is located Address
  102. $offset = $this->getlong3();
  103. fseek($this->fp, $offset);
  104. $location['endip'] = long2ip($this->getlong()); / / End address of the user IP range
  105. $byte = fread($this->fp, 1); // Flag byte
  106. switch (ord($byte)) {
  107. case 1: // Flag byte is 1 , indicating that both country and regional information are redirected at the same time
  108. $countryOffset = $this->getlong3(); // Redirect address
  109. fseek($this->fp, $countryOffset);
  110. $byte = fread($ this->fp, 1); // Flag byte
  111. switch (ord($byte)) {
  112. case 2: // Flag byte is 2, indicating that the country information has been redirected again
  113. fseek($this-> ;fp, $this->getlong3());
  114. $location['country'] = $this->getstring();
  115. fseek($this->fp, $countryOffset + 4);
  116. $location ['area'] = $this->getarea();
  117. break;
  118. default: // Otherwise, it means that the country information is not redirected
  119. $location['country'] = $this->getstring($byte );
  120. $location['area'] = $this->getarea();
  121. break;
  122. }
  123. break;
  124. case 2: // The flag byte is 2, indicating that the country information is redirected
  125. fseek($ this->fp, $this->getlong3());
  126. $location['country'] = $this->getstring();
  127. fseek($this->fp, $offset + 8);
  128. $location['area'] = $this->getarea();
  129. break;
  130. default: // Otherwise, it means that the country information is not redirected
  131. $location['country'] = $this->getstring ($byte);
  132. $location['area'] = $this->getarea();
  133. break;
  134. }
  135. if ($location['country'] == " CZ88.NET") { // CZ88 .NET indicates that there is no valid information
  136. $location['country'] = "Unknown";
  137. }
  138. if ($location['area'] == " CZ88.NET") {
  139. $location['area'] = " ";
  140. }
  141. return $location;
  142. }
  143. /**
  144. * Destructor, used to automatically close the open file after the page execution ends.
  145. *
  146. */
  147. function __desctruct() {
  148. if ($this->fp) {
  149. fclose($this->fp);
  150. }
  151. $this->fp = 0;
  152. }
  153. }
  154. ?>
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool