PHP: Remote IP + Load Balancer
PHP + Code Igniter: How to Get Remote IP Behind Load Balancer
Because most PHP opensource software assumes that your web server is directly exposed the to the Internet, I find that I have to alter the code often to get the actual remote ip address. Why? Because my company’s servers are behind a load balancer. In our configuration, X-HTTP-CLIENT-IP is the header that the load balancer passes to the actual web server. I’ve been using codeigniter a lot lately and luckily, code igniter is easily extended. The following code needs to reside in your system/applications/library folder. It needs to be named MY_Input.php (unless you changed the MY_ prefix.)
This code simply goes through the list of possible matches for remote ip (even from proxy servers.) I really don’t depend on it for anything other than logging, so I’m not worried by the security implications.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /*** Brett: Fri Sep 19 23:18:46 GMT 2008 * Extension to Input class to correctly get netscaler remote ip address ***/ class MY_Input extends CI_Input { function ip_address() { if ($this->ip_address !== FALSE) { return $this->ip_address; } if ($this->server('HTTP_X_CLIENTIP')) { $this->ip_address = $_SERVER['HTTP_X_CLIENTIP']; } elseif ($this->server('REMOTE_ADDR') AND $this->server('HTTP_CLIENT_IP')) { $this->ip_address = $_SERVER['HTTP_CLIENT_IP']; } elseif ($this->server('REMOTE_ADDR')) { $this->ip_address = $_SERVER['REMOTE_ADDR']; } elseif ($this->server('HTTP_CLIENT_IP')) { $this->ip_address = $_SERVER['HTTP_CLIENT_IP']; } elseif ($this->server('HTTP_X_FORWARDED_FOR')) { $this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR']; } if ($this->ip_address === FALSE) { $this->ip_address = '0.0.0.0'; return $this->ip_address; } if (strstr($this->ip_address, ',')) { $x = explode(',', $this->ip_address); $this->ip_address = end($x); } if ( ! $this->valid_ip($this->ip_address)) { $this->ip_address = '0.0.0.0'; } return $this->ip_address; } } ?> |