How to get the client IP address using PHP
Snippet
To get the client IP address, PHP provides a server variable $_SERVER
. The $_SERVER
can contain keys with IP.
function getClientIP(){
foreach (['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 (isset($_SERVER[$key])){
foreach (explode(',', $_SERVER[$key]) as $ip){
$ip = trim($ip);
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
return $ip;
}
}
}
}
return null;
}
echo getClientIP();