Reliability of PHP'S $_SERVER['REMOTE_ADDR']

后端 未结 3 2053
慢半拍i
慢半拍i 2020-12-31 13:03

I\'m building a site that is designed to be administered from localhost, but contains pages that expose data to internet or local network users. Can I rely on PHP\'s

3条回答
  •  情歌与酒
    2020-12-31 13:43

    This may not typically apply to connections from localhost but you should take proxies into account. If the remote end is using a HTTP proxy, $_SERVER['REMOTE_ADDR'] will contain the IP address of that proxy rather than the IP address of the client itself.

    However, if it is a proxy which has privacy settings disabled, then you may have a chance to obtain client IP using the following snippet:

    // will be set by the proxy if no privacy is enabled:
    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if(isset($_SERVER['REMOTE_ADDR'])) {
        return $_SERVER['REMOTE_ADDR'];
    }
    

    But if your client is using a HTTP proxy with privacy enabled, then you won't have a chance to get the clients IP.


    Security Hint (thanks @deceze) Note that if you rely on the HTTP_X_FORWARDED_FOR header, it will be easy for attackers to spoof their IP. Although this is possible using other techniques as well, it will be very easy using the HTTP_X_FORWARDED_FOR header. You have been warned. But anyway an web application should never use IP information for security, therefore it's just a side-note

提交回复
热议问题