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.
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.
This is the most advanced method I have found, already tried some others in the past. Valid to ensure to get the IP address of visitor (but please note that any hacker could falsify ip address easily).
source: http://blackbe.lt/advanced-method-to-obtain-the-client-ip-in-php/
The answer is to use
$_SERVER
variable. For example,$_SERVER["REMOTE_ADDR"]
would return the client's IP address.http://php.net/manual/en/reserved.variables.server.php
Here is the one-liner version getting the client's IP address:
Notes:
@
, it suppresses the PHP notices.Value from
HTTP_X_FORWARDED_FOR
may consist multiple addresses separated by comma, so if you prefer to get the first one, you can use the following method:$_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:
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
try this one