1
0

getIP.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. /*
  3. * This script detects the client's IP address and fetches ISP info from ipinfo.io/
  4. * Output from this script is a JSON string composed of 2 objects: a string called processedString which contains the combined IP, ISP, Country and distance as it can be presented to the user; and an object called rawIspInfo which contains the raw data from ipinfo.io (or an empty string if isp detection is disabled or if it failed).
  5. * Client side, the output of this script can be treated as JSON or as regular text. If the output is regular text, it will be shown to the user as is.
  6. */
  7. error_reporting(0);
  8. define('API_KEY_FILE', 'getIP_ipInfo_apikey.php');
  9. define('SERVER_LOCATION_CACHE_FILE', 'getIP_serverLocation.php');
  10. define('OFFLINE_IPINFO_DB_FILE', 'country_asn.mmdb');
  11. require_once 'getIP_util.php';
  12. function getLocalOrPrivateIpInfo($ip){
  13. // ::1/128 is the only localhost ipv6 address. there are no others, no need to strpos this
  14. if ('::1' === $ip) {
  15. return 'localhost IPv6 access';
  16. }
  17. // simplified IPv6 link-local address (should match fe80::/10)
  18. if (stripos($ip, 'fe80:') === 0) {
  19. return 'link-local IPv6 access';
  20. }
  21. // fc00::/7 Unique Local IPv6 Unicast Addresses
  22. if (preg_match('/^(fc|fd)([0-9a-f]{0,4}:){1,7}[0-9a-f]{1,4}$/i', $ip) === 1) {
  23. return 'ULA IPv6 access';
  24. }
  25. // anything within the 127/8 range is localhost ipv4, the ip must start with 127.0
  26. if (strpos($ip, '127.') === 0) {
  27. return 'localhost IPv4 access';
  28. }
  29. // 10/8 private IPv4
  30. if (strpos($ip, '10.') === 0) {
  31. return 'private IPv4 access';
  32. }
  33. // 172.16/12 private IPv4
  34. if (preg_match('/^172\.(1[6-9]|2\d|3[01])\./', $ip) === 1) {
  35. return 'private IPv4 access';
  36. }
  37. // 192.168/16 private IPv4
  38. if (strpos($ip, '192.168.') === 0) {
  39. return 'private IPv4 access';
  40. }
  41. // IPv4 link-local
  42. if (strpos($ip, '169.254.') === 0) {
  43. return 'link-local IPv4 access';
  44. }
  45. return null;
  46. }
  47. function getIspInfo_ipinfoApi($ip){
  48. if (!file_exists(API_KEY_FILE) || !is_readable(API_KEY_FILE)){
  49. return null;
  50. }
  51. require API_KEY_FILE;
  52. if(empty($IPINFO_APIKEY)){
  53. return null;
  54. }
  55. $json = file_get_contents('https://ipinfo.io/' . $ip . '/json?token=' . $IPINFO_APIKEY);
  56. if (!is_string($json)) {
  57. return null;
  58. }
  59. $data = json_decode($json, true);
  60. if (!is_array($data)) {
  61. return null;
  62. }
  63. $isp=null;
  64. //ISP name, if present, is either in org or asn.name
  65. if (array_key_exists('org', $data) && is_string($data['org']) && !empty($data['org'])) {
  66. // Remove AS##### from ISP name, if present
  67. $isp = preg_replace('/AS\\d+\\s/', '', $data['org']);
  68. } elseif (array_key_exists('asn', $data) && is_array($data['asn']) && !empty($data['asn']) && array_key_exists('name', $data['asn']) && is_string($data['asn']['name'])) {
  69. $isp = $data['asn']['name'];
  70. } else{
  71. return null;
  72. }
  73. $country=null;
  74. if(array_key_exists('country',$data) && is_string($data['country'])){
  75. $country = $data['country'];
  76. }
  77. //If requested by the client (and we have the required information), calculate the distance
  78. $distance=null;
  79. if(isset($_GET['distance']) && ($_GET['distance']==='mi' || $_GET['distance']==='km') && array_key_exists('loc', $data) && is_string($data['loc'])){
  80. $unit = $_GET['distance'];
  81. $clientLoc = $data['loc'];
  82. $serverLoc = null;
  83. if (file_exists(SERVER_LOCATION_CACHE_FILE) && is_readable(SERVER_LOCATION_CACHE_FILE)) {
  84. require SERVER_LOCATION_CACHE_FILE;
  85. }
  86. if (!is_string($serverLoc) || empty($serverLoc)) {
  87. $json = file_get_contents('https://ipinfo.io/json?token=' . $IPINFO_APIKEY);
  88. if (!is_string($json)) {
  89. return null;
  90. }
  91. $sdata = json_decode($json, true);
  92. if (!is_array($sdata) || !array_key_exists('loc', $sdata) || !is_string($sdata['loc']) || empty($sdata['loc'])) {
  93. return null;
  94. }
  95. $serverLoc = $sdata['loc'];
  96. file_put_contents(SERVER_LOCATION_CACHE_FILE, "<?php\n\n\$serverLoc = '" . addslashes($serverLoc) . "';\n");
  97. }
  98. list($clientLatitude, $clientLongitude) = explode(',', $clientLoc);
  99. list($serverLatitude, $serverLongitude) = explode(',', $serverLoc);
  100. //distance calculation adapted from http://www.codexworld.com
  101. $rad = M_PI / 180;
  102. $dist = acos(sin($clientLatitude * $rad) * sin($serverLatitude * $rad) + cos($clientLatitude * $rad) * cos($serverLatitude * $rad) * cos(($clientLongitude - $serverLongitude) * $rad)) / $rad * 60 * 1.853;
  103. if ($unit === 'mi') {
  104. $dist /= 1.609344;
  105. $dist = round($dist, -1);
  106. if ($dist < 15) {
  107. $dist = '<15';
  108. }
  109. $distance = $dist . ' mi';
  110. }elseif ($unit === 'km') {
  111. $dist = round($dist, -1);
  112. if ($dist < 20) {
  113. $dist = '<20';
  114. }
  115. $distance = $dist . ' km';
  116. }
  117. }
  118. $processedString=$ip.' - '.$isp;
  119. if(is_string($country)){
  120. $processedString.=', '.$country;
  121. }
  122. if(is_string($distance)){
  123. $processedString.=' ('.$distance.')';
  124. }
  125. return json_encode([
  126. 'processedString' => $processedString,
  127. 'rawIspInfo' => $data ?: '',
  128. ]);
  129. }
  130. if (PHP_MAJOR_VERSION >= 8){
  131. require_once("geoip2.phar");
  132. }
  133. function getIspInfo_ipinfoOfflineDb($ip){
  134. if (!file_exists(OFFLINE_IPINFO_DB_FILE) || !is_readable(OFFLINE_IPINFO_DB_FILE)){
  135. return null;
  136. }
  137. $reader = new MaxMind\Db\Reader(OFFLINE_IPINFO_DB_FILE);
  138. $data = $reader->get($ip);
  139. if(!is_array($data)){
  140. return null;
  141. }
  142. $processedString = $ip.' - ' . $data['as_name'] . ', ' . $data['country_name'];
  143. return json_encode([
  144. 'processedString' => $processedString,
  145. 'rawIspInfo' => $data ?: '',
  146. ]);
  147. }
  148. function formatResponse_simple($ip,$ispName=null){
  149. $processedString=$ip;
  150. if(is_string($ispName)){
  151. $processedString.=' - '.$ispName;
  152. }
  153. return json_encode([
  154. 'processedString' => $processedString,
  155. 'rawIspInfo' => '',
  156. ]);
  157. }
  158. header('Content-Type: application/json; charset=utf-8');
  159. if (isset($_GET['cors'])) {
  160. header('Access-Control-Allow-Origin: *');
  161. header('Access-Control-Allow-Methods: GET, POST');
  162. }
  163. header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
  164. header('Cache-Control: post-check=0, pre-check=0', false);
  165. header('Pragma: no-cache');
  166. $ip = getClientIp();
  167. //if the user requested the ISP info, we first try to fetch it using ipinfo.io (if there is no api key set it fails without sending data, it can also fail because of rate limiting or invalid responses), then we try with the offline db, if that also fails (or if ISP info was not requested) we just respond with the IP address
  168. if(isset($_GET['isp'])){
  169. $localIpInfo = getLocalOrPrivateIpInfo($ip);
  170. //local ip, no need to fetch further information
  171. if (is_string($localIpInfo)) {
  172. echo formatResponse_simple($ip,$localIpInfo);
  173. }else{
  174. //ipinfo API and offline db require PHP 8 or newer
  175. if (PHP_MAJOR_VERSION >= 8){
  176. $r=getIspInfo_ipinfoApi($ip);
  177. if(!is_null($r)){
  178. echo $r;
  179. }else{
  180. $r=getIspInfo_ipinfoOfflineDb($ip);
  181. if(!is_null($r)){
  182. echo $r;
  183. }else{
  184. echo formatResponse_simple($ip);
  185. }
  186. }
  187. }else{
  188. echo formatResponse_simple($ip);
  189. }
  190. }
  191. }else{
  192. echo formatResponse_simple($ip);
  193. }