getIP.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 (will be empty if isp detection is disabled).
  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. require_once 'getIP_util.php';
  11. /**
  12. * @param string $ip
  13. *
  14. * @return string|null
  15. */
  16. function getLocalOrPrivateIpInfo($ip)
  17. {
  18. // ::1/128 is the only localhost ipv6 address. there are no others, no need to strpos this
  19. if ('::1' === $ip) {
  20. return 'localhost IPv6 access';
  21. }
  22. // simplified IPv6 link-local address (should match fe80::/10)
  23. if (stripos($ip, 'fe80:') === 0) {
  24. return 'link-local IPv6 access';
  25. }
  26. // anything within the 127/8 range is localhost ipv4, the ip must start with 127.0
  27. if (strpos($ip, '127.') === 0) {
  28. return 'localhost IPv4 access';
  29. }
  30. // 10/8 private IPv4
  31. if (strpos($ip, '10.') === 0) {
  32. return 'private IPv4 access';
  33. }
  34. // 172.16/12 private IPv4
  35. if (preg_match('/^172\.(1[6-9]|2\d|3[01])\./', $ip) === 1) {
  36. return 'private IPv4 access';
  37. }
  38. // 192.168/16 private IPv4
  39. if (strpos($ip, '192.168.') === 0) {
  40. return 'private IPv4 access';
  41. }
  42. // IPv4 link-local
  43. if (strpos($ip, '169.254.') === 0) {
  44. return 'link-local IPv4 access';
  45. }
  46. return null;
  47. }
  48. /**
  49. * @return string
  50. */
  51. function getIpInfoTokenString()
  52. {
  53. if (
  54. !file_exists(API_KEY_FILE)
  55. || !is_readable(API_KEY_FILE)
  56. ) {
  57. return '';
  58. }
  59. require API_KEY_FILE;
  60. if (empty($IPINFO_APIKEY)) {
  61. return '';
  62. }
  63. return '?token='.$IPINFO_APIKEY;
  64. }
  65. /**
  66. * @param string $ip
  67. *
  68. * @return array|null
  69. */
  70. function getIspInfo($ip)
  71. {
  72. $json = file_get_contents('https://ipinfo.io/'.$ip.'/json'.getIpInfoTokenString());
  73. if (!is_string($json)) {
  74. return null;
  75. }
  76. $data = json_decode($json, true);
  77. if (!is_array($data)) {
  78. return null;
  79. }
  80. return $data;
  81. }
  82. /**
  83. * @param array|null $rawIspInfo
  84. *
  85. * @return string
  86. */
  87. function getIsp($rawIspInfo)
  88. {
  89. if (
  90. !is_array($rawIspInfo)
  91. || !array_key_exists('org', $rawIspInfo)
  92. || !is_string($rawIspInfo['org'])
  93. || empty($rawIspInfo['org'])
  94. ) {
  95. return 'Unknown ISP';
  96. }
  97. // Remove AS##### from ISP name, if present
  98. return preg_replace('/AS\\d+\\s/', '', $rawIspInfo['org']);
  99. }
  100. /**
  101. * @return string|null
  102. */
  103. function getServerLocation()
  104. {
  105. $serverLoc = null;
  106. if (
  107. file_exists(SERVER_LOCATION_CACHE_FILE)
  108. && is_readable(SERVER_LOCATION_CACHE_FILE)
  109. ) {
  110. require SERVER_LOCATION_CACHE_FILE;
  111. }
  112. if (is_string($serverLoc) && !empty($serverLoc)) {
  113. return $serverLoc;
  114. }
  115. $json = file_get_contents('https://ipinfo.io/json'.getIpInfoTokenString());
  116. if (!is_string($json)) {
  117. return null;
  118. }
  119. $details = json_decode($json, true);
  120. if (
  121. !is_array($details)
  122. || !array_key_exists('loc', $details)
  123. || !is_string($details['loc'])
  124. || empty($details['loc'])
  125. ) {
  126. return null;
  127. }
  128. $serverLoc = $details['loc'];
  129. $cacheData = "<?php\n\n\$serverLoc = '".addslashes($serverLoc)."';\n";
  130. file_put_contents(SERVER_LOCATION_CACHE_FILE, $cacheData);
  131. return $serverLoc;
  132. }
  133. /**
  134. * Optimized algorithm from http://www.codexworld.com
  135. *
  136. * @param float $latitudeFrom
  137. * @param float $longitudeFrom
  138. * @param float $latitudeTo
  139. * @param float $longitudeTo
  140. *
  141. * @return float [km]
  142. */
  143. function distance(
  144. $latitudeFrom,
  145. $longitudeFrom,
  146. $latitudeTo,
  147. $longitudeTo
  148. ) {
  149. $rad = M_PI / 180;
  150. $theta = $longitudeFrom - $longitudeTo;
  151. $dist = sin($latitudeFrom * $rad)
  152. * sin($latitudeTo * $rad)
  153. + cos($latitudeFrom * $rad)
  154. * cos($latitudeTo * $rad)
  155. * cos($theta * $rad);
  156. return acos($dist) / $rad * 60 * 1.853;
  157. }
  158. /**
  159. * @param array|null $rawIspInfo
  160. *
  161. * @return string|null
  162. */
  163. function getDistance($rawIspInfo)
  164. {
  165. if (
  166. !is_array($rawIspInfo)
  167. || !array_key_exists('loc', $rawIspInfo)
  168. || !isset($_GET['distance'])
  169. || !in_array($_GET['distance'], ['mi', 'km'], true)
  170. ) {
  171. return null;
  172. }
  173. $unit = $_GET['distance'];
  174. $clientLocation = $rawIspInfo['loc'];
  175. $serverLocation = getServerLocation();
  176. if (!is_string($serverLocation)) {
  177. return null;
  178. }
  179. return calculateDistance(
  180. $serverLocation,
  181. $clientLocation,
  182. $unit
  183. );
  184. }
  185. /**
  186. * @param string $clientLocation
  187. * @param string $serverLocation
  188. * @param string $unit
  189. *
  190. * @return string
  191. */
  192. function calculateDistance($clientLocation, $serverLocation, $unit)
  193. {
  194. list($clientLatitude, $clientLongitude) = explode(',', $clientLocation);
  195. list($serverLatitude, $serverLongitude) = explode(',', $serverLocation);
  196. $dist = distance(
  197. $clientLatitude,
  198. $clientLongitude,
  199. $serverLatitude,
  200. $serverLongitude
  201. );
  202. if ('mi' === $unit) {
  203. $dist /= 1.609344;
  204. $dist = round($dist, -1);
  205. if ($dist < 15) {
  206. $dist = '<15';
  207. }
  208. return $dist.' mi';
  209. }
  210. if ('km' === $unit) {
  211. $dist = round($dist, -1);
  212. if ($dist < 20) {
  213. $dist = '<20';
  214. }
  215. return $dist.' km';
  216. }
  217. return null;
  218. }
  219. /**
  220. * @return void
  221. */
  222. function sendHeaders()
  223. {
  224. header('Content-Type: application/json; charset=utf-8');
  225. if (isset($_GET['cors'])) {
  226. header('Access-Control-Allow-Origin: *');
  227. header('Access-Control-Allow-Methods: GET, POST');
  228. }
  229. header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
  230. header('Cache-Control: post-check=0, pre-check=0', false);
  231. header('Pragma: no-cache');
  232. }
  233. /**
  234. * @param string $ip
  235. * @param string|null $ipInfo
  236. * @param string|null $distance
  237. * @param array|null $rawIspInfo
  238. *
  239. * @return void
  240. */
  241. function sendResponse(
  242. $ip,
  243. $ipInfo = null,
  244. $distance = null,
  245. $rawIspInfo = null
  246. ) {
  247. $processedString = $ip;
  248. if (is_string($ipInfo)) {
  249. $processedString .= ' - '.$ipInfo;
  250. }
  251. if (
  252. is_array($rawIspInfo)
  253. && array_key_exists('country', $rawIspInfo)
  254. ) {
  255. $processedString .= ', '.$rawIspInfo['country'];
  256. }
  257. if (is_string($distance)) {
  258. $processedString .= ' ('.$distance.')';
  259. }
  260. sendHeaders();
  261. echo json_encode([
  262. 'processedString' => $processedString,
  263. 'rawIspInfo' => $rawIspInfo ?: '',
  264. ]);
  265. }
  266. $ip = getClientIp();
  267. $localIpInfo = getLocalOrPrivateIpInfo($ip);
  268. // local ip, no need to fetch further information
  269. if (is_string($localIpInfo)) {
  270. sendResponse($ip, $localIpInfo);
  271. exit;
  272. }
  273. if (!isset($_GET['isp'])) {
  274. sendResponse($ip);
  275. exit;
  276. }
  277. $rawIspInfo = getIspInfo($ip);
  278. $isp = getIsp($rawIspInfo);
  279. $distance = getDistance($rawIspInfo);
  280. sendResponse($ip, $isp, $distance, $rawIspInfo);