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 {
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


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?


thephpdeveloper said...

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

Anonymous said...

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

thephpdeveloper said...

hi gururaj

thanks a lot.

Sankar lp said...

I have read your blog its very attractive and impressive. I like it your blog.

PHP 7 Training in chennai | PHP 7 Training Course

PHP 7 Training in chennai | Online PHP 7 Course