如何在 Laravel 5+ 中获取客户端 IP 地址 [英] How to get client IP address in Laravel 5+
本文介绍了如何在 Laravel 5+ 中获取客户端 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 Laravel 中获取客户端的 IP 地址.
I am trying to get the client's IP address in Laravel.
在 PHP 中使用 $_SERVER["REMOTE_ADDR"]
很容易获取客户端的 IP.它在核心 PHP 中运行良好,但是当我在 Laravel 中使用相同的东西时,它返回服务器 IP 而不是访问者的 IP.
It is easy to get a client's IP in PHP by using $_SERVER["REMOTE_ADDR"]
. It is working fine in core PHP, but when I use the same thing in Laravel, it returns the server IP instead of the visitor's IP.
推荐答案
查看 Laravel API:
Request::ip();
在内部,它使用 getClientIps 方法"noreferrer">Symfony 请求对象:
Internally, it uses the getClientIps
method from the Symfony Request Object:
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);
}
这篇关于如何在 Laravel 5+ 中获取客户端 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文