tags:

views:

815

answers:

3

Hi,

I am trying to grab a users' IP address to show them content relevant to their geography. I used the php code $ip = getenv('REMOTE_ADDR'); to grab their IP address. This works fine on my computer but my co-developer tried it and found that he was unable to connect to our site at all and got a "Host Not Accessible" error. He is unable to connect to our site via FTP as well or from another computer at his house.

I took out this code and he still couldn't connect (but could using a proxy). I am wondering why this code would have these side effects. Is $_SERVER('REMOTE_ADDR'). Whats the best way to grab a user's IP address in PHP?

Thanks

Russ

+7  A: 
  1. That code doesn't have side effects. The problem your coworker is seeing is more likely a firewall/connectivity/server configuration issue.
  2. Using $_SERVER is indeed the proper way to get those variables' values.
Vinko Vrsalovic
A: 

I blame your co-developers DNS or /etc/hosts setup.

André Hoffmann
+2  A: 

http://thephpcode.blogspot.com/2009/01/php-getting-secondary-internet-protocol.html

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;
}

At least this code gets you the actual IP address even from users behind ISP proxies and so on.

thephpdeveloper
Mind you, HTTP_X_FORWARDED_FOR might contain multiple addresses.
MathieuK
well if you are getting a string, why not? but MahtieuK - great point there.
thephpdeveloper