PHP most efficient way to get real user IP in 2017

0 投票
最新提问 用户: (320 分)

What is the most accurate way to get user's IP in 2017 via PHP?

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 usafe.

For example at this question (2011): How to get the client IP address in PHP?

Tim Kennedy's answer recommended to use something like:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
} else {
    $ip = $_SERVER['REMOTE_ADDR'];

But as I've read a lot I seen that use X_FORWARDED_FOR is unsafe, as comment below this answer:

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.

As I didn't know EXACTLY what it does, I don't want to risk. He told that It is unsafe, but not provided safe method to get user's IP.

I've tried simple use $_SERVER['REMOTE_ADDR'];, but It get wrong IP. I've tested It and my real IP is like:, but It shows my IP address like:

So you have any ideas?

发表于 用户: (140 分) ... its Your Public Ip ... and its your pc ip.
发表于 用户: (140 分)
发表于 用户: (320 分)
@RïshïKêshKümar so yes, my IP is like 78.57...., but $_SERVER['REMOTE_ADDR']; resturns me like 81.7.....
发表于 用户: (140 分)
$_SERVER['REMOTE_HOST'] .... try this ... what you get

3 个回答

0 投票
最新回答 用户: (140 分)

Get Client IP Address:

 echo   $ip = $_SERVER['REMOTE_ADDR'];

Note:: This would work only on live site, because on your local host your ip would be one (1) of the internal ip addresses, like So, its Return ::1

Example :

Its Show Your Local Ip: Like ...


$myIp= getHostByName(php_uname('n'));
 echo $myIp;
发表于 用户: (100 分)
But question is about user IP, not local
0 投票
最新回答 用户: (260 分)

A code like yours is the only way to retrieve a client IP. You have just to apply a filter_var to it (beacause it can be Tampered, as pointed by your quote).

This can be a good source to make a correct and secure code.

0 投票
最新回答 用户: (140 分)

I use this code, and it works for me. Take a look to it.


// Gets client's IP.
$ip = getenv("HTTP_CLIENT_IP")?:

echo $ip;


Here, a working example. Hope it helps!

欢迎来到 Security Q&A ,有什么不懂的可以尽管在这里提问,你将会收到社区其他成员的回答。