How to get the client IP address in PHP [duplicate]

This question already has an answer here:

How can I get the client IP address using PHP?

I want to keep record of the user who logged into my website through his/her IP address.

1 Like

$_SERVER['REMOTE_ADDR'] may not actually contain real client IP addresses, as it will give you a proxy address for clients connected through a proxy, for example. That may well be what you really want, though, depending what your doing with the IPs. Someone’s private RFC1918 address may not do you any good if you’re say, trying to see where your traffic is originating from, or remembering what IP the user last connected from, where the public IP of the proxy or NAT gateway might be the more appropriate to store.

There are several HTTP headers like X-Forwarded-For which may or may not be set by various proxies. The problem is that those are merely HTTP headers which can be set by anyone. There’s no guarantee about their content. $_SERVER['REMOTE_ADDR'] is the actual physical IP address that the web server received the connection from and that the response will be sent to. Anything else is just arbitrary and voluntary information. There’s only one scenario in which you can trust this information: you are controlling the proxy that sets this header. Meaning only if you know 100% where and how the header was set should you heed it for anything of importance.

Having said that, here’s some sample code:

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

Editor’s note: Using the above code has security implications . The client can set all HTTP header information (ie. $_SERVER['HTTP_... ) to any arbitrary value it wants. As such it’s far more reliable to use $_SERVER['REMOTE_ADDR'] , as this cannot be set by the user.

From: http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html

Refer: https://stackoverflow.com/questions/3003145/how-to-get-the-client-ip-address-in-php