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;
}As a result, this function can return one of two values:
1. The user's IP address
2. NULL, if the IP could not be determined
Let’s take a closer look at the example above. The following functions are used in the listing:
getenv() — Gets the value of an environment variable
strcasecmp() — Performs a binary-safe case-insensitive string comparison
empty() — Checks whether a variable is empty
In the environment variables `getenv("HTTP_CLIENT_IP")` or `getenv("HTTP_X_FORWARDED_FOR")`, the original IP address of the user is stored. It all depends on the proxy server itself. Depending on its configuration, it may either return the user's IP or not return it at all. After running a small test with two proxy servers, it was found that these variables were empty.
However, the following constructions:
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'];
}Will return either the user's real IP address or the IP address of the proxy server.
And in case of failure, the function will return NULL for more accurate data handling.
