getIP.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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['X-Real-IP'])) {
  18. $ip = $_SERVER['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 (!file_exists(API_KEY_FILE)) {
  70. return '';
  71. }
  72. require API_KEY_FILE;
  73. if (empty($IPINFO_APIKEY)) {
  74. return '';
  75. }
  76. return '?token='.$IPINFO_APIKEY;
  77. }
  78. /**
  79. * @param string $ip
  80. *
  81. * @return array|null
  82. */
  83. function getIspInfo($ip)
  84. {
  85. $json = file_get_contents('https://ipinfo.io/'.$ip.'/json'.getIpInfoTokenString());
  86. if (!is_string($json)) {
  87. return null;
  88. }
  89. $data = json_decode($json, true);
  90. if (!is_array($data)) {
  91. return null;
  92. }
  93. return $data;
  94. }
  95. /**
  96. * @param array|null $rawIspInfo
  97. *
  98. * @return string
  99. */
  100. function getIsp($rawIspInfo)
  101. {
  102. if (
  103. !is_array($rawIspInfo)
  104. || !array_key_exists('org', $rawIspInfo)
  105. || !is_string($rawIspInfo['org'])
  106. || empty($rawIspInfo['org'])
  107. ) {
  108. return 'Unknown ISP';
  109. }
  110. // Remove AS##### from ISP name, if present
  111. return preg_replace('/AS\\d+\\s/', '', $rawIspInfo['org']);
  112. }
  113. /**
  114. * @return string|null
  115. */
  116. function getServerLocation()
  117. {
  118. $serverLoc = null;
  119. if (file_exists(SERVER_LOCATION_CACHE_FILE)) {
  120. require SERVER_LOCATION_CACHE_FILE;
  121. }
  122. if (is_string($serverLoc) && !empty($serverLoc)) {
  123. return $serverLoc;
  124. }
  125. $json = file_get_contents('https://ipinfo.io/json'.getIpInfoTokenString());
  126. if (!is_string($json)) {
  127. return null;
  128. }
  129. $details = json_decode($json, true);
  130. if (
  131. !is_array($details)
  132. || !array_key_exists('loc', $details)
  133. || !is_string($details['loc'])
  134. || empty($details['loc'])
  135. ) {
  136. return null;
  137. }
  138. $serverLoc = $details['loc'];
  139. $cacheData = "<?php\n\n\$serverLoc = '".addslashes($serverLoc)."';\n";
  140. file_put_contents(SERVER_LOCATION_CACHE_FILE, $cacheData);
  141. return $serverLoc;
  142. }
  143. /**
  144. * Optimized algorithm from http://www.codexworld.com
  145. *
  146. * @param float $latitudeFrom
  147. * @param float $longitudeFrom
  148. * @param float $latitudeTo
  149. * @param float $longitudeTo
  150. *
  151. * @return float [km]
  152. */
  153. function distance(
  154. $latitudeFrom,
  155. $longitudeFrom,
  156. $latitudeTo,
  157. $longitudeTo
  158. ) {
  159. $rad = M_PI / 180;
  160. $theta = $longitudeFrom - $longitudeTo;
  161. $dist = sin($latitudeFrom * $rad)
  162. * sin($latitudeTo * $rad)
  163. + cos($latitudeFrom * $rad)
  164. * cos($latitudeTo * $rad)
  165. * cos($theta * $rad);
  166. return acos($dist) / $rad * 60 * 1.853;
  167. }
  168. /**
  169. * @param array|null $rawIspInfo
  170. *
  171. * @return string|null
  172. */
  173. function getDistance($rawIspInfo)
  174. {
  175. if (
  176. !is_array($rawIspInfo)
  177. || !array_key_exists('loc', $rawIspInfo)
  178. || !isset($_GET['distance'])
  179. || !in_array($_GET['distance'], ['mi', 'km'], true)
  180. ) {
  181. return null;
  182. }
  183. $unit = $_GET['distance'];
  184. $clientLocation = $rawIspInfo['loc'];
  185. $serverLocation = getServerLocation();
  186. if (!is_string($serverLocation)) {
  187. return null;
  188. }
  189. return calculateDistance(
  190. $serverLocation,
  191. $clientLocation,
  192. $unit
  193. );
  194. }
  195. /**
  196. * @param string $clientLocation
  197. * @param string $serverLocation
  198. * @param string $unit
  199. *
  200. * @return string
  201. */
  202. function calculateDistance($clientLocation, $serverLocation, $unit)
  203. {
  204. list($clientLatitude, $clientLongitude) = explode(',', $clientLocation);
  205. list($serverLatitude, $serverLongitude) = explode(',', $serverLocation);
  206. $dist = distance(
  207. $clientLatitude,
  208. $clientLongitude,
  209. $serverLatitude,
  210. $serverLongitude
  211. );
  212. if ('mi' === $unit) {
  213. $dist /= 1.609344;
  214. $dist = round($dist, -1);
  215. if ($dist < 15) {
  216. $dist = '<15';
  217. }
  218. return $dist.' mi';
  219. }
  220. if ('km' === $unit) {
  221. $dist = round($dist, -1);
  222. if ($dist < 20) {
  223. $dist = '<20';
  224. }
  225. return $dist.' km';
  226. }
  227. return null;
  228. }
  229. /**
  230. * @return void
  231. */
  232. function sendHeaders()
  233. {
  234. header('Content-Type: application/json; charset=utf-8');
  235. if (isset($_GET['cors'])) {
  236. header('Access-Control-Allow-Origin: *');
  237. header('Access-Control-Allow-Methods: GET, POST');
  238. }
  239. header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
  240. header('Cache-Control: post-check=0, pre-check=0', false);
  241. header('Pragma: no-cache');
  242. }
  243. /**
  244. * @param string $ip
  245. * @param string|null $ipInfo
  246. * @param string|null $distance
  247. * @param array|null $rawIspInfo
  248. *
  249. * @return void
  250. */
  251. function sendResponse(
  252. $ip,
  253. $ipInfo = null,
  254. $distance = null,
  255. $rawIspInfo = null
  256. ) {
  257. $processedString = $ip;
  258. if (is_string($ipInfo)) {
  259. $processedString .= ' - '.$ipInfo;
  260. }
  261. if (
  262. is_array($rawIspInfo)
  263. && array_key_exists('country', $rawIspInfo)
  264. ) {
  265. $processedString .= ', '.$rawIspInfo['country'];
  266. }
  267. if (is_string($distance)) {
  268. $processedString .= ' ('.$distance.')';
  269. }
  270. sendHeaders();
  271. echo json_encode([
  272. 'processedString' => $processedString,
  273. 'rawIspInfo' => $rawIspInfo ?: '',
  274. ]);
  275. }
  276. $ip = getClientIp();
  277. $localIpInfo = getLocalOrPrivateIpInfo($ip);
  278. // local ip, no need to fetch further information
  279. if (is_string($localIpInfo)) {
  280. sendResponse($ip, $localIpInfo);
  281. exit;
  282. }
  283. if (!isset($_GET['isp'])) {
  284. sendResponse($ip);
  285. exit;
  286. }
  287. $rawIspInfo = getIspInfo($ip);
  288. $isp = getIsp($rawIspInfo);
  289. $distance = getDistance($rawIspInfo);
  290. sendResponse($ip, $isp, $distance, $rawIspInfo);