diff --git a/src/Support/IpSupport.php b/src/Support/IpSupport.php new file mode 100644 index 0000000..9bab372 --- /dev/null +++ b/src/Support/IpSupport.php @@ -0,0 +1,81 @@ +ok()) { + $ipAddress = $response->json()['ip'] ?? null; + + if (!empty($ipAddress)) { + return $ipAddress; + } + } + + return $ipAddress; + } + + /** + * Get client real IP address + * + * @source https://stackoverflow.com/q/13646690/6940144 + * + * @param bool $getLocalPublicIp + * + * @return string + */ + public static function getIP(bool $getLocalPublicIp = true): string + { + $baseIp = $_SERVER['REMOTE_ADDR']; + + try { + // get localhost public ip + if ($getLocalPublicIp && self::isLocalhost()) { + return self::getLocalhostPublicIp(); + } + + // check other conditions, cloudflare etc + if (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && filter_var($_SERVER['HTTP_CF_CONNECTING_IP'], FILTER_VALIDATE_IP)) { + return $_SERVER['HTTP_CF_CONNECTING_IP']; + } elseif (isset($_SERVER['HTTP_X_REAL_IP']) && filter_var($_SERVER['HTTP_X_REAL_IP'], FILTER_VALIDATE_IP)) { + return $_SERVER['HTTP_X_REAL_IP']; + } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) { + return $_SERVER['HTTP_CLIENT_IP']; + } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { + return $_SERVER['HTTP_X_FORWARDED_FOR']; + } + } catch (Exception $exp) { + Log::alert('getIP error', ['error' => $exp]); + } + + return $baseIp; + } +}