1

I am using below code to get the user's real IP address.

function getUserIP () { if (getenv('HTTP_CLIENT_IP')) { $ip = getenv('HTTP_CLIENT_IP'); } elseif (getenv('HTTP_X_FORWARDED_FOR')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); } elseif (getenv('HTTP_X_FORWARDED')) { $ip = getenv('HTTP_X_FORWARDED'); } elseif (getenv('HTTP_FORWARDED_FOR')) { $ip = getenv('HTTP_FORWARDED_FOR'); } elseif (getenv('HTTP_FORWARDED')) { $ip = getenv('HTTP_FORWARDED'); } else { $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } $userIP = getUserIP(); 

Sometimes I am getting that the IP address is 67.143.220.112, 67.142.171.26.

Is that the correct IP address of the user or do I have to do something else to get the real IP address of the user?

2

3 Answers 3

4

$_SERVER['REMOTE_ADDR']; gives the user's IP address.

Sign up to request clarification or add additional context in comments.

1 Comment

It only gives the address of the machine which originated the TCP connection to the server, which may NOT be the user's actual address.
2

Perfect method to get User IP address.

<?PHP function getUserIP() { $client = @$_SERVER['HTTP_CLIENT_IP']; $forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; $remote = $_SERVER['REMOTE_ADDR']; if(filter_var($client, FILTER_VALIDATE_IP)) { $ip = $client; } elseif(filter_var($forward, FILTER_VALIDATE_IP)) { $ip = $forward; } else { $ip = $remote; } return $ip; } $user_ip = getUserIP(); echo $user_ip; // Output User IP address [Ex: 177.87.193.134] ?> 

Comments

1

The only 100% reliable address you can get is $_SERVER['REMOTE_ADDR']. The other headers are optional, not always present, and are trivially forged, since they're informational only.

Even the REMOTE_ADDR one will be wrong if the user is behind one or more proxies and/or NAT gateways. In short, there's no foolproof way to perfectly identify a user's real IP address regardless of proxying/NATing.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.