Get Visitor's IP using PHP - Most Accurated
by PRanesh[ Edit ] 2013-07-25 18:05:33
$ip=$_SERVER['REMOTE_ADDR'];
echo $ip;
In above code variable ip holds visitor's ip.
Some cases, for example if a request comes through proxy above code will give you
Server ip instead of visitors. To evade from such
situations you can use following code.
public function get_ip(){
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $ip){
$ip = trim($ip); // just to be safe
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
return $ip;
}
}
}
}
}
$ip= get_ip();
This code will check for shared ips,proxies and gives you the actual ip of a client.