Skip to content
Advertisement

PHP most accurate / safe way to get real user IP address in 2017

What is the most accurate way to get user’s IP address 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 unsafe.

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

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'];
}

But as I’ve read a lot, I have seen that to use X_FORWARDED_FOR is unsafe, as the comment below highlights:

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 take the risk. He said it is unsafe, but did not provide a safe method to get user’s IP address.

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

So do you have any ideas?

Advertisement

Answer

Short answer:

$ip = $_SERVER['REMOTE_ADDR'];


As of 2021 (and still) $_SERVER['REMOTE_ADDR']; is the only reliable way 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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement