Reputation: 101
I have to get public IP of the remote system in php. I have tried
$_SERVER['REMOTE_ADDR']
getenv('REMOTE_ADDR');
but is always returning the private IP. Help to fix it.
Upvotes: 0
Views: 1386
Reputation: 34
private function getIP()
{
$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;
}
echo getIP();
Upvotes: 0
Reputation: 1422
Try this:
$ip = !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
Warning: you should extend it and sanitize, since headers can be easily manipulated.
Upvotes: 1