gpt4 book ai didi

php - 如何在 Laravel 5+ 中获取客户端 IP 地址

转载 作者:IT老高 更新时间:2023-10-28 11:49:40 26 4
gpt4 key购买 nike

我正在尝试在 Laravel 中获取客户端的 IP 地址。

使用 $_SERVER["REMOTE_ADDR"] 可以很容易地在 PHP 中获取客户端的 IP。它在核心 PHP 中运行良好,但是当我在 Laravel 中使用相同的东西时,它返回服务器 IP 而不是访问者的 IP。

最佳答案

Laravel API :

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);
}

关于php - 如何在 Laravel 5+ 中获取客户端 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33268683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com