Advertisement
mnakos

Resolve real public clients ip address behind reverse proxy

Apr 14th, 2016
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.98 KB | None | 0 0
  1. // Function that decides to return as remote address the HTTP_X_FORWARDED_FOR (if exists) for cases of reverse proxy
  2. function Actual_REMOTE_ADDR()
  3. {
  4.     // DEFINE HERE THE IP ADDRESSE(s) OF REVERSE PROXY(s)
  5.     $reverse_proxy_addresses = array('15.14.13.1');
  6.    
  7.     $client_address = $_SERVER['REMOTE_ADDR'];
  8.    
  9.     // Check if resolved REMOTE_ADDR is one of the reverse proxy address
  10.     $revpr_found = in_array($client_address, $reverse_proxy_addresses);
  11.    
  12.     // If so, try to get the HTTP_X_FORWARDED_FOR value of the request's header
  13.     if($revpr_found)
  14.     {
  15.         if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] !== "")
  16.         {
  17.             $client_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
  18.             $client_arr = explode(",", $client_address);
  19.            
  20.             // It happens, for some networks, if app is behind reverse proxy, $client_address to have 2 values
  21.             // Must get the first one only
  22.             if(count($client_arr) > 1)
  23.                 $client_address = $client_arr[0];
  24.         }
  25.     }
  26.    
  27.     return $client_address;
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement