PHP working behind proxies.

When coding behind a proxy there are some challenges when it comes to user management and sessions management. Also many people think that when they are behind a proxy they cant be traced. Well to be clear, there are no secrets when it comes to IP information.

Many applications i viewed are 9/10 times using $_SERVER['remote_addr'] to find the visiting client IP address. In most cases this will work as designed up till the point the application is put behind a proxy. In this situation the logged IP address will always be the one held by the proxy server.

Luckily every proxy server will add a new headers we can utilize to find the IP held be the client. These header are respectively;

"HTTP_X_FORWARDED_FOR"  Contains the remote client IP for which the forward was performed.
"HTTP_X_FORWARDED_HOST" Contains the address of the responsible proxy server.
"HTTP_X_FORWARDED_SERVER" Contains the FQDN of the responsible proxy server.

When using these header in conjunction with the allready much utilized "REMOTE_ADDR" we can easly define a function to fetch the true remote address, even when being accessed through a proxy.

                      function getRemoteIP(){
                      	$xFor    = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : false;
                      	$xHost   = (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : false;
                          $rAddr   = (isset($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : false;	
                      		return ($xFor != $rAddr) ? $xFor : $rAddr;
                      		return $rAddr;
                      echo getRemoteIP();

Open in new window

How to find the visitors IP address?

Always consider the fact that you, the visitor of any other daemon or bot might be using proxies in an attempt to conceal them selfs. When your applications policy is not to allow this, then you might also utilize these headers to block these connection attempts and or generate warnings.

Hope these headers will help you make better and more secure applications ;-)


Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.