rkljw 1 天之前
父节点
当前提交
398f4482a0
共有 1 个文件被更改,包括 23 次插入5 次删除
  1. 23 5
      app/Controller/PublicController.php

+ 23 - 5
app/Controller/PublicController.php

@@ -1325,14 +1325,32 @@ class PublicController extends AbstractController
      */
     public function getIpInfo()
     {
-
-        $ip = $this->request->getHeader('x-forwarded-for')[0] ?? $this->request->getHeader('x-real-ip')[0] ?? $this->request->getServerParams()['remote_addr'] ?? '0.0.0.0';
-        var_dump("========",$ip);
-        $result = $this->publicServiceClient->getIpInfo(['ip'=>$ip]);
-        var_dump("========",$result);
+        $ip = $this->getClientIp();
+        $result = $this->publicServiceClient->getIpInfo(['ip' => $ip]);
         return $result['code'] == 200 ? Result::success($result['data']) : Result::error($result['message']);
     }
 
+    /**
+     * 获取客户端IP地址.
+     * @return string
+     */
+    private function getClientIp(): string
+    {
+        if ($this->request->hasHeader('x-forwarded-for')) {
+            $ip = trim(explode(',', $this->request->getHeaderLine('x-forwarded-for'))[0]);
+            if ($ip) {
+                return $ip;
+            }
+        }
+        if ($this->request->hasHeader('x-real-ip')) {
+            $ip = $this->request->getHeaderLine('x-real-ip');
+            if ($ip) {
+                return $ip;
+            }
+        }
+        return $this->request->getServerParams()['remote_addr'] ?? '0.0.0.0';
+    }
+
     /**
      * 获取天气信息
      * @return array