PHP code used in website returns network IP of user and not public IP

548 Views Asked by At

I have PHP code that is supposed to detect a user's IP address. The code below returns an IP address, but the IP address is sometimes a local network IP (e.g. 10.0.0.1) and not a public IP. How can I ensure that I always get the public IP? Thanks. BTW, this code is from another StackOverflow post. Also, this code is used in a website that is being accessed over the internet from a completely separate network than that of my Apache web server.

if (isset($_SERVER["HTTP_CLIENT_IP"])){  
  $ip = $_SERVER["HTTP_CLIENT_IP"];  
} elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){  
  $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];  
} elseif (isset($_SERVER["HTTP_X_FORWARDED"])){  
  $ip = $_SERVER["HTTP_X_FORWARDED"];  
} elseif (isset($_SERVER["HTTP_FORWARDED_FOR"])){  
  $ip = $_SERVER["HTTP_FORWARDED_FOR"];  
} elseif (isset($_SERVER["HTTP_FORWARDED"])){  
  $ip = $_SERVER["HTTP_FORWARDED"];  
} else {   
  $ip = $_SERVER["REMOTE_ADDR"];  
}
1

There are 1 best solutions below

0
Ben D On

Eliminate all the if(){} else{} code, and just request the REMOTE_ADDR:

 $ip =  $_SERVER["REMOTE_ADDR"];

It's the only reliable source of a user's remote IP address as all the other _SERVER keys can be masked by the client.

If the IP address is still local (and youre SURE that you're dealing with clients not in the networks or on a local VPN) the you may be dealing with either a server caching system (Squid Proxy eg). Have a look at http://www.nineteenlabs.com/2007/08/24/high-anonymous-proxy-squid-25/