IP.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. /**
  3. * IP 信息
  4. *
  5. * @author luolongf <[email protected]>
  6. * @date 2022-05-14
  7. * @time 8:28
  8. */
  9. namespace Luolongfei\Libs;
  10. use GuzzleHttp\Client;
  11. class IP extends Base
  12. {
  13. const TIMEOUT = 2.14;
  14. /**
  15. * 匹配 ip 的正则
  16. */
  17. const REGEX_IP = '/(?:\d{1,3}\.){3}\d{1,3}/u';
  18. const REGEX_LOC = '/^.*:(?P<country>[^\s]+?)\s+?(?P<region>[^\s]+?)\s+?(?P<city>[^\s]+?)\s/iu';
  19. /**
  20. * @var string ip 地址
  21. */
  22. public static $ip = '';
  23. /**
  24. * @var string 位置信息
  25. */
  26. public static $loc = '';
  27. /**
  28. * @var Client
  29. */
  30. protected $client;
  31. /**
  32. * @var string 用于查询 ip 的地址
  33. */
  34. protected $url;
  35. public function init()
  36. {
  37. $this->client = new Client([
  38. 'headers' => [
  39. 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36',
  40. ],
  41. 'cookies' => false,
  42. 'timeout' => self::TIMEOUT,
  43. 'verify' => config('verify_ssl'),
  44. 'debug' => config('debug'),
  45. ]);
  46. $this->url = is_chinese() ? 'https://myip.ipip.net' : 'https://ipinfo.io/json';
  47. }
  48. /**
  49. * @return string
  50. * @throws \GuzzleHttp\Exception\GuzzleException
  51. */
  52. public function get()
  53. {
  54. try {
  55. if (!self::$ip && !self::$loc) {
  56. $res = $this->client->get($this->url);
  57. $body = $res->getBody()->getContents();
  58. $this->matchIpInfo($body);
  59. }
  60. return sprintf(lang('100130'), self::$ip, self::$loc);
  61. } catch (\Exception $e) {
  62. Log::error(lang('100132') . $e->getMessage());
  63. return lang('100131');
  64. }
  65. }
  66. /**
  67. * 匹配 ip 信息
  68. *
  69. * @param $body
  70. *
  71. * @return bool
  72. */
  73. protected function matchIpInfo($body)
  74. {
  75. if (is_chinese()) {
  76. if (preg_match(self::REGEX_IP, $body, $m)) {
  77. self::$ip = $m[0];
  78. }
  79. if (preg_match(self::REGEX_LOC, $body, $m)) {
  80. self::$loc = sprintf('%s %s %s', $m['country'], $m['region'], $m['city']);
  81. }
  82. return true;
  83. }
  84. $body = (array)json_decode($body, true);
  85. self::$ip = $body['ip'] ?? '';
  86. self::$loc = sprintf('%s %s %s', $body['country'] ?? '', $body['region'] ?? '', $body['city'] ?? '');
  87. return true;
  88. }
  89. }