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

不羁的心 提交于 2020-02-05 07:29:54

问题


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?


回答1:


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




回答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]


?>



回答3:


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.



来源:https://stackoverflow.com/questions/5919160/how-to-get-a-users-ip-address-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!