【问题标题】:Getting Client's IP in laravellaravel获取客户端IP
【发布时间】:2020-12-08 12:34:15
【问题描述】:

我是网站开发的新手。

我需要获取客户端的 IP 地址。 我检查了类似的问题https://stackoverflow.com/questions/33268683/how-to-get-client-ip-address-in-laravel-5 但看不懂。

我使用了request()->ip(),但它每次都给了我谷歌云的 ip,因为网站在它上面,而 127.0.0.1 在本地。 我想获取访问我网站的客户的 ip()。 如何获得?

我使用了$myPublicIP = trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));,它在本地给了我我的公共 IP 地址。当我在谷歌云上上传我的代码时这会起作用吗 ?

还有谁能告诉我$myPublicIP = trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));这个命令是如何工作的?

【问题讨论】:

标签: php laravel ip ipv4


【解决方案1】:

这一行:

$myPublicIP = trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));

不检查访问者 IP。您正在从命令运行程序(又名您/您的服务器)检查 IP。

现在,$request->ip() 只读取 REMOTE_ADDR 标头属性。

我没有使用过 Google Cloud,我不确定它的行为,但是如果您获取的是 Google Cloud 的 IP 而不是用户的 IP,那一定是因为它作为代理工作并且它没有转发真实用户 IP。

我想应该有办法告诉 Google Cloud 在请求中转发访问者 IP。

【讨论】:

    【解决方案2】:

    如果你使用的是谷歌云的负载均衡器,相信你可以从$_SERVER['X-Forwarded-For']访问转发的IP地址。

    https://cloud.google.com/load-balancing/docs/https#x-forwarded-for_header

    【讨论】:

    • 在本地使用$_SERVER['X-Forwarded-For']时,会给出"Undefined index: X-Forwarded-For"这是为什么呢?
    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 2013-10-16
    • 2014-10-06
    • 2019-01-14
    • 2012-03-31
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多