本文介绍了如何在Laravel 5+中获取客户端IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Laravel中获取客户端的IP地址.
I am trying to get the client's IP address in Laravel.
使用$_SERVER["REMOTE_ADDR"]
可以很容易地在PHP中获得客户端的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();
在内部,它使用 Symfony中的getClientIps
方法请求对象:
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地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!