getIP.php 7.8 KB

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