Retrieving the best IP


Keep in mind that obtaining the visitors IP address is somewhat like asking a shady person to hold your wallet… But still many people use it as a type of identification for visitors. The problem is, most of the time, coders are looking at only 1 possible way of obtaining the very volatile piece of information. When in reality there are many different methods which may be defined by anyone with 33 and 1/3% of a brain.

But… since the above disclosure was announced, a better method of obtaining an IP address is by looping through HTTP_X_FORWARDED_FOR, HTTP_NS_CLIENT_IP, HTTP_CLIENT_IP and REMOTE_ADDR. just to name a few. Here is a script that I wrote several years ago to actually set your IP SERVER constants into an array, and actually process them for possible local IP’s then gather the most probable solution and return it accordingly.

function getIP(){
$bestIP = ‘’;
$bestLocalIP = ‘’;
foreach($ipvars as $ipvar){
$ip = isset($_SERVER[$ipvar]) ? $_SERVER[$ipvar] : null;
if($ip && stripos($ip,‘unknown’)!==0 && strpos($ip,‘127.’)!==0 && strpos($ip,‘10.’)!==0 && strpos($ip,‘172.16.’)!==0 && strpos($ip,‘192.168.’)!==0 && stripos($ip,‘localhost’)!==0){
$bestIP = $bestIP==’’ ? $ip : $bestIP;
} elseif($ip && (strpos($ip,‘127.’)===0 || strpos($ip,‘10.’)===0 || strpos($ip,‘172.16.’)===0 || strpos($ip,‘192.168.’)===0 || stripos($ip,‘localhost’)===0)){
$bestLocalIP = $bestLocalIP==’’ ? $ip : $bestLocalIP;

$ip = ($bestIP != '' ? $bestIP : ($bestLocalIP != '' ? $bestLocalIP : 'unknown'));
return $ip;