Get real client IP

X-Forwarded-For: client1, proxy1, proxy2, proxy3

Where the value + space by a comma to separate multiple IP addresses area, the left-most (client1) is the most original client's IP address, proxy server every successful receipt of a request, the request to put the source IP address to the right. In the above example, the request by the three successful proxy server: proxy1, proxy2 and proxy3. Request is issued by client1, it reached proxy3 (proxy3 endpoint may be requested). When the request is made just client1, XFF is empty, the request is sent to proxy1; proxy1 by time, is added to client1 XFF, after which the request is sent to proxy2; proxy2 by time, it is added to proxy1 XFF in after the request is sent to the proxy3; through proxy3, proxy2 be added to XFF, after which the request is unaccounted for, will continue to be forwarded if the request is not the end proxy3 request.

If a request arrives before the HTTP server, through three agents Proxy1, Proxy2, Proxy3, IP respectively IP1, IP2, IP3, users real IP is IP0, then in accordance with XFF standard, the server will eventually receive this message: X- Forwarded-For: IP0, IP1, IP2

In view of this field is very easy to forge, should be used with caution X-Forwarded-For field. XFF last IP address is the last IP address of the proxy server under normal circumstances, this is usually a more reliable source of information.

// Get different real environment the IP 
function get_ip () {
     // determines whether the server allows _SERVER $ 
    IF ( isset ( $ _SERVER )) {    
         IF ( isset ( $ _SERVER [HTTP_X_FORWARDED_FOR])) {
             $ realip = $ _SERVER [HTTP_X_FORWARDED_FOR ]; 
        } ELSEIF ( isset ( $ _SERVER [HTTP_CLIENT_IP])) {
             $ realip = $ _SERVER [HTTP_CLIENT_IP]; 
        } the else {
             $ realip = $ _SERVER[REMOTE_ADDR];
        }
    }else{
        //不允许就使用getenv获取  
        if(getenv("HTTP_X_FORWARDED_FOR")){
              $realip = getenv( "HTTP_X_FORWARDED_FOR");
        }elseif(getenv("HTTP_CLIENT_IP")) {
              $realip = getenv("HTTP_CLIENT_IP");
        }else{
              $realip = getenv("REMOTE_ADDR");
        }
    }

    return $realip;
}   

getenv function name is taken from the environment string, obtaining the environment variable value, getenv () for acquiring content parameter envvar environment variable. Envvar parameter is the name of the environment variable, if the variable exists it will point to the content of the return pointer . Format environment variable is envvar = value. getenv function's return value is stored in a global two-dimensional array, when you use the getenv function again have to worry about covering the results of the last call.

 

Guess you like

Origin www.cnblogs.com/hanmengya/p/11025513.html