$_SERVER[“REMOTE_ADDR”] gives server IP rather than visitor IP

后端 未结 8 765
小蘑菇
小蘑菇 2020-11-28 05:55

I\'m trying to track IP addresses of visitors. When using $_SERVER[\"REMOTE_ADDR\"], I get the server\'s IP address rather than the visitor\'s. I tried this on

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 06:27

    With PHP 7.4 I do it like this:

    $ipaddress = '';
    if (isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    

    But keep in mind that REMOTE_ADDR is the only reliable IP address that you can get. All other values can easily be manipulated. This is theoretically also possible for REMOTE_ADDRESS, but that would require to spoof the IP address.

提交回复
热议问题