-1

So i'm having this code `

$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;
echo '<script>console.log("'.$ip.'")</script>';

`

I want to get visitor's ip but every time it returns false ips. So anyone knows how to solve this problem , or what is the reason ? I also think it could be server-side or hosting problem

E_net4
  • 27,810
  • 13
  • 101
  • 139
Tiko
  • 1,241
  • 11
  • 19
  • Not technically relevant, but remember that using user's IP addresses could be against the [GDPR](https://en.wikipedia.org/wiki/General_Data_Protection_Regulation), depending on the context. Consider if you _really_ need to get this information in the first place. – domsson Jan 18 '20 at 09:07

1 Answers1

-1

Replace your server variable declaration with followings:

$client  = (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) ? $_SERVER['HTTP_CLIENT_IP'] : '';
$forward  = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
$remote  = (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : '';

It will declare+assign it by blank value if unset.

Farhan
  • 253
  • 2
  • 9
  • No it still returns other false ips – Tiko Jan 18 '20 at 09:14
  • If you are fine to use third party services following js code can be used `** var settings = { "url": "https://api.ipify.org?format=json", "method": "GET", "timeout": 0, }; $.ajax(settings).done(function (response) { console.log(response); }); **` – Farhan Jan 18 '20 at 09:41
  • after almost 2 years, it's still not correct – Tiko Oct 19 '21 at 11:11