How to get client IP in PHP? [duplicate]

3

I have already researched in several forums and even here but none of the solutions I have seen have brought me the correct result. In all the attempts I get as ip :: 1

Follow the code I'm using

<?php

  if (!empty($_SERVER['HTTP_CLIENT_IP']))   
    {
      $ip_address = $_SERVER['HTTP_CLIENT_IP'];
    }
  elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  
    {
      $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
  else
    {
      $ip_address = $_SERVER['REMOTE_ADDR'];
    }
  echo $ip_address;
?>
    
asked by anonymous 14.09.2017 / 17:27

1 answer

1

Try this code:

<?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 IP address [Ex: 177.87.193.134]


?>

Do not forget to not access your page through the https://localhost link, instead, access the www.nomedoseusite.com link if you're hosted or IP :

https://192.168.0.1 //Seu número de IP
    
14.09.2017 / 17:38