开发者

How to get a user's IP address in PHP?

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

function getUserIP () {

    if (geten开发者_如何学编程v('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?


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


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]


?>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜