Skip to content

Commit 1d2745f

Browse files
committed
Add IpSupport class
1 parent 54155ce commit 1d2745f

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

src/Support/IpSupport.php

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<?php
2+
3+
namespace LaravelReady\UltimateSupport\Support;
4+
5+
use Exception;
6+
7+
use Illuminate\Support\Facades\Log;
8+
use Illuminate\Support\Facades\Http;
9+
10+
class IpSupport
11+
{
12+
/**
13+
* Check client is from localhost
14+
*
15+
* @source https://stackoverflow.com/a/21702853/6940144
16+
*
17+
* @return bool
18+
*/
19+
public static function isLocalhost(): bool
20+
{
21+
return in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1', '172.27.0.1']);
22+
}
23+
24+
/**
25+
* Get client public IP address if it is localhost
26+
*
27+
* @return null | string
28+
*/
29+
public static function getLocalhostPublicIp(): null | string
30+
{
31+
$ipAddress = null;
32+
33+
$response = Http::get('https://api.ipify.org/?format=json');
34+
35+
if ($response->ok()) {
36+
$ipAddress = $response->json()['ip'] ?? null;
37+
38+
if (!empty($ipAddress)) {
39+
return $ipAddress;
40+
}
41+
}
42+
43+
return $ipAddress;
44+
}
45+
46+
/**
47+
* Get client real IP address
48+
*
49+
* @source https://stackoverflow.com/q/13646690/6940144
50+
*
51+
* @param bool $getLocalPublicIp
52+
*
53+
* @return string
54+
*/
55+
public static function getIP(bool $getLocalPublicIp = true): string
56+
{
57+
$baseIp = $_SERVER['REMOTE_ADDR'];
58+
59+
try {
60+
// get localhost public ip
61+
if ($getLocalPublicIp && self::isLocalhost()) {
62+
return self::getLocalhostPublicIp();
63+
}
64+
65+
// check other conditions, cloudflare etc
66+
if (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && filter_var($_SERVER['HTTP_CF_CONNECTING_IP'], FILTER_VALIDATE_IP)) {
67+
return $_SERVER['HTTP_CF_CONNECTING_IP'];
68+
} elseif (isset($_SERVER['HTTP_X_REAL_IP']) && filter_var($_SERVER['HTTP_X_REAL_IP'], FILTER_VALIDATE_IP)) {
69+
return $_SERVER['HTTP_X_REAL_IP'];
70+
} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) {
71+
return $_SERVER['HTTP_CLIENT_IP'];
72+
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
73+
return $_SERVER['HTTP_X_FORWARDED_FOR'];
74+
}
75+
} catch (Exception $exp) {
76+
Log::alert('getIP error', ['error' => $exp]);
77+
}
78+
79+
return $baseIp;
80+
}
81+
}

0 commit comments

Comments
 (0)