我正在尝试获取客户端在Laravel中的IP地址。
在PHP中使用$_SERVER["REMOTE_ADDR"]可以很容易地获取客户端的IP地址。它在核心PHP中工作得很好,但当我在Laravel中使用相同的东西时,它返回服务器IP而不是访问者的IP。
发布于 2015-10-22 04:35:05
Request::ip();在内部,它使用Symfony Request Object中的getClientIps方法
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);
} 发布于 2015-12-10 23:00:05
使用request()->ip()。
据我所知,从Laravel 5开始,建议/良好的做法是使用如下全局函数:
response()->json($v);
view('path.to.blade');
redirect();
route();
cookie();而且,如果有什么不同的话,那就是当使用函数而不是静态表示法时,我的IDE不会像圣诞树一样亮起来。
发布于 2016-01-19 17:42:07
添加命名空间
use Request;然后调用该函数
Request::ip();https://stackoverflow.com/questions/33268683
复制相似问题