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?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • Use $_SERVER['REMOTE_ADDR'] Also, may i suggest [switch](http://php.net/manual/en/control-structures.switch.php) for clarity? – Jordan Arsenault May 07 '11 at 05:25
  • Your way seems fine. For a more detailed blog discussion : http://www.scriptygoddess.com/archives/2003/03/18/get-users-ip-with-php/ – Spyros May 07 '11 at 04:48

3 Answers3

4

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

Kenny Linsky
  • 1,726
  • 3
  • 17
  • 41
leszek77
  • 83
  • 9
  • 1
    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. – Marc B May 07 '11 at 05:21
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]


?>
Temüjin
  • 15,371
  • 8
  • 35
  • 57
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.

Marc B
  • 356,200
  • 43
  • 426
  • 500