PHP是2017年获得真实用户IP地址的最准确/最安全的方式 [英] PHP most accurate / safe way to get real user IP address in 2017
问题描述
2017年通过PHP获取用户IP地址的最准确方法是什么?
What is the most accurate way to get user's IP address in 2017 via PHP?
我已经阅读了很多关于它的SO问题和答案,但大多数用户认为这些方法是不安全的,答案是陈旧的。
I've read a lot of SO questions and answers about it, but most of answers are old and commented by users that these ways are unsafe.
例如,看看这个问题(2011):如何在PHP中获取客户端IP地址?
For example, take a look at this question (2011): How to get the client IP address in PHP?
Tim Kennedy的答案包含建议使用类似:
Tim Kennedy's answer contains a recommendation to use something like:
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
但是我已经阅读了很多内容,我已经看到要使用 X_FORWARDED_FOR
是不安全的,因为下面的评论突出显示:
But as I've read a lot, I have seen that to use X_FORWARDED_FOR
is unsafe, as the comment below highlights:
请勿使用上述代码除非你完全知道它的作用!由于这个原因,我已经看到了大量的安全漏洞。客户端可以将
X-Forwarded-For或Client-IP标头设置为
想要的任意值。除非你有一个可信的反向代理,否则你不应该使用这些值的任何
。
Do NOT use the above code unless you know EXACTLY what it does! I've seen MASSIVE security holes due to this. The client can set the X-Forwarded-For or the Client-IP header to any arbitrary value it wants. Unless you have a trusted reverse proxy, you shouldn't use any of those values.
因为我没有确切地知道它的作用,我不想承担风险。他说它不安全,但没有提供安全的方法来获取用户的IP地址。
As I didn't know EXACTLY what it does, I don't want to take the risk. He said it is unsafe, but did not provide a safe method to get user's IP address.
我尝试过简单的 $ _ SERVER [' REMOTE_ADDR'];
,但这会返回错误的IP。我已经测试了这个,我的真实IP遵循这种模式: 78.57.xxx.xxx
,但我得到的IP地址如下: 81.7.xxx。 xxx
I've tried the simple $_SERVER['REMOTE_ADDR'];
, but this returns the wrong IP. I've tested this and my real IP follows this pattern: 78.57.xxx.xxx
, but I get an IP address like: 81.7.xxx.xxx
您有什么想法吗?
推荐答案
简答:
$ ip = $ _SERVER ['REMOTE_ADDR'];
截至 2018 $ _ SERVER [' REMOTE_ADDR'];
是获取用户IP地址唯一可靠的解决方案,但如果在代理服务器后面,它可能会显示错误的结果。
所有其他解决方案意味着安全风险,或者容易伪造。
As of 2018 $_SERVER['REMOTE_ADDR'];
is the only reliable solution to get users ip address, but it can show erroneous results if behind a proxy server.
All other solutions imply security risks or can be easily faked.
这篇关于PHP是2017年获得真实用户IP地址的最准确/最安全的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!