Created
August 22, 2022 05:26
-
-
Save shahednur/b40ee2048ee62b87fb65118db23808e7 to your computer and use it in GitHub Desktop.
Laravel Eloquent Model Accessor to get Client/User IP Address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function getClientIps() | |
{ | |
$clientIps = array(); | |
$ip = $this->server->get('REMOTE_ADDR'); | |
if (!$this->isFromTrustedProxy()) { | |
return array($ip); | |
} | |
if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) { | |
$forwardedHeader = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]); | |
preg_match_all('{(for)=("?\[?)([a-z0-9\.:_\-/]*)}', $forwardedHeader, $matches); | |
$clientIps = $matches[3]; | |
} elseif (self::$trustedHeaders[self::HEADER_CLIENT_IP] && $this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) { | |
$clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP]))); | |
} | |
$clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from | |
$ip = $clientIps[0]; // Fallback to this when the client IP falls into the range of trusted proxies | |
foreach ($clientIps as $key => $clientIp) { | |
// Remove port (unfortunately, it does happen) | |
if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) { | |
$clientIps[$key] = $clientIp = $match[1]; | |
} | |
if (IpUtils::checkIp($clientIp, self::$trustedProxies)) { | |
unset($clientIps[$key]); | |
} | |
} | |
// Now the IP chain contains only untrusted proxies and the client IP | |
return $clientIps ? array_reverse($clientIps) : array($ip); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment