In this article, we’ll look at one of the common tasks in PHP programming — specifically, how to determine the user's IP address in PHP.
If I’m not working with a framework (such as Yii), I use one of the ready-made solutions in the form of the following function:
function user_ip()
{
if(getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"),"unknown"))
{
return getenv("HTTP_CLIENT_IP");
}
else if(getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
{
return getenv("HTTP_X_FORWARDED_FOR");
}
else if(getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
{
return getenv("REMOTE_ADDR");
}
else if(!empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
{
return $_SERVER['REMOTE_ADDR'];
}
return NULL;
}

