mnakos icon

Resolve real public clients ip address behind reverse proxy

mnakos | PRO | 04/14/16 01:10:16 PM UTC | 0 ⭐ | 360 👁️ | Never ⏰ | []
PHP |

980 B

|

None

|

0 👍

/

0 👎

// Function that decides to return as remote address the HTTP_X_FORWARDED_FOR (if exists) for cases of reverse proxy
function Actual_REMOTE_ADDR()
{
    // DEFINE HERE THE IP ADDRESSE(s) OF REVERSE PROXY(s)
    $reverse_proxy_addresses = array('15.14.13.1');
    
    $client_address = $_SERVER['REMOTE_ADDR'];
    
    // Check if resolved REMOTE_ADDR is one of the reverse proxy address
    $revpr_found = in_array($client_address, $reverse_proxy_addresses);
    
    // If so, try to get the HTTP_X_FORWARDED_FOR value of the request's header
    if($revpr_found)
    {
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] !== "")
        {
            $client_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
            $client_arr = explode(",", $client_address);
            
            // It happens, for some networks, if app is behind reverse proxy, $client_address to have 2 values
            // Must get the first one only
            if(count($client_arr) > 1)
                $client_address = $client_arr[0];
        }
    }
    
    return $client_address;
}

Comments