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.
As all others said before you can use
$_SERVER['REMOTE_ADDR'];
to get client IP address.Also, if you need more information about a user, you can use this:
Client's more specific info goes in $clientDetails.
You can fetch json items stored in $clientDetails variable this way: $clientDetails->PostalCode/hostname/region/loc...
I'm using ipinfo.io to get extra info.
I hope it helps.
Here's a simple one liner
EDIT:
Above code may return reserved addresses (like 10.0.0.1), a list of addresses of all proxy servers on the way, etc. To handle these cases use the following code:
Safe and warnings aware snippet for getting IP:
My favourite solution is the way Zend Framework 2 uses. It also considers the
$_SERVER
propertiesHTTP_X_FORWARDED_FOR
,HTTP_CLIENT_IP
,REMOTE_ADDR
but it declares a class for it to set some trusted proxies and it returns one IP address not an array. I think this is the solution that comes closest to it:See the full code here: https://raw.githubusercontent.com/zendframework/zend-http/master/src/PhpEnvironment/RemoteAddress.php