简体   繁体   中英

$_SERVER['REMOTE_ADDR'] gives the IP Address of the server instead of the IP Address of the user

EDIT:

I have cleaned the cache of my browser and now my PHP Code is working.


I know that there are already similar questions and that i cannot trust in $_SERVER['REMOTE_ADDR'] to get the real IP Address of a visitor.

I am testing my website on localhost and i am not behind any proxy, i am trying to display my IP Address but $_SERVER['REMOTE_ADDR'] gives 127.0.0.1 , namely the IP Address of the server.

If i put the samecode online in my server, i receive again the IP Address of the server.

I have tried without success with:

function get_visitor_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress .= $_SERVER['HTTP_CLIENT_IP'] . ' - ';
    }
    if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipaddress .= $_SERVER['HTTP_X_FORWARDED_FOR']. ' - ';
    }
    if(isset($_SERVER['HTTP_X_FORWARDED'])) {
        $ipaddress .= $_SERVER['HTTP_X_FORWARDED']. ' - ';
    }
    if(isset($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ipaddress .= $_SERVER['HTTP_FORWARDED_FOR']. ' - ';
    }
    if(isset($_SERVER['HTTP_FORWARDED'])) {
        $ipaddress .= $_SERVER['HTTP_FORWARDED']. ' - ';
    }
    if(isset($_SERVER['REMOTE_ADDR'])) {
        $ipaddress .= $_SERVER['REMOTE_ADDR']. ' - ';
    }

    if($ipaddress == '') {
        $ipaddress = 'UNKNOWN';
    }

    return $ipaddress;
}

But again, it returns 127.0.0.1 . Any alternative solution?

This means your server is probably behind some sort of reverse proxy, like a load balancer or CDN. Your PHP server is not receiving direct connections from clients, those connections go through some intermediate before, so the IP of that intermediate is all your server sees.

In this situation the intermediate proxy typically forwards the actual client's IP in some specified HTTP header to your PHP server. That is when you very explicitly and very selectively use something like $_SERVER['HTTP_X_FORWARDED'] ; if and only if and when you know that you're in this kind of situation and which HTTP header you can trust. Consult the documentation of your host/proxy/network situation and it'll tell you what header to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM