Before reading this article, you should know that HTTP_X_FORWARDED_FOR should only be used for websites behind a proxy, otherwise you should use REMOTE_ADDR!! This article talks about getting the right visitor IP through HTTP_X_FORWARDED_FOR for applications behind a reverse proxy!
You might have faced it as it’s not so well documented. Note that i’m using nginx as reverse proxy, and this may not be the case with all the servers.
Yes HTTP_X_FORWARDED_FOR might return multiple IPs. And i’ve read multiple bogus statements on internet saying the first IP is the right one. This is incorrect.
The first IP may be the real client behind many proxies, but it can be fake (modified through headers).
So what is correct is to get the LAST IP from the list of IPs, which is the IP that connected to your (reverse) proxy, this is what you probably need in 99% of cases, trust me.
Here is the code in PHP:
$ip_array=explode(“,”, $_SERVER[‘HTTP_X_FORWARDED_FOR’]);
$remoteip=trim($ip_array[count($ip_array)-1]);