Tuesday, January 13, 2009

PHP: Getting Secondary Internet Protocol (IP) Address

You'll probably get the Remote IP Address of your users by using the server variable $_SERVER['REMOTE_ADDR']. However, if your users are being proxy servers or using dynamic IP address, you won't get the actual IP Address of your users using $_SERVER['REMOTE_ADDR'].

Probably you need the following code to help you to get the actual IP address of your users.

function getIP() {
$IP = '';
if (getenv('HTTP_CLIENT_IP')) {$IP =getenv('HTTP_CLIENT_IP');}
elseif (getenv('HTTP_X_FORWARDED_FOR')) {$IP =getenv('HTTP_X_FORWARDED_FOR');}
elseif (getenv('HTTP_X_FORWARDED')) {$IP =getenv('HTTP_X_FORWARDED');}
elseif (getenv('HTTP_FORWARDED_FOR')) {$IP =getenv('HTTP_FORWARDED_FOR');}
elseif (getenv('HTTP_FORWARDED')) {$IP = getenv('HTTP_FORWARDED');}
else {
$IP = $_SERVER['REMOTE_ADDR'];
}
return $IP;
}


How does this get the actual IP?
When servers send data to a client through a proxy, the protocol will still send the actual IP address through the environment variables in order for the proxy to be able to identify which client to send to.

You should use this abreast (side by side) with $_SERVER['REMOTE_ADDR']. This function returns $_SERVER['REMOTE_ADDR'] if there's no secondary IP address.

Pastebin: http://thephpcode.pastebin.com/f24c2ec13

6 comments:

mancala said...

Thank you very much. I have been searching for this for a while. it will be very useful on my site for votes www.stcardio.com

thephpdeveloper said...

no problem at all mancala!

gamers2000 said...

Hey Sam,
Thanks for the tip! :D
Question though. This would probably work for transparent proxies, but how about anonymous proxies that do not send the originating IP?

-Joel

thephpdeveloper said...

@Joel - if they are determined to hide it rom you, then you probably won't get to retrieve the IP address.

Gururaj said...

This is a very nice piece of code in PHP.
seo company

thephpdeveloper said...

hi gururaj

thanks a lot.