When developing with PHP, it’s often necessary to identify the user’s IP address. The simplest way is to use the `$_SERVER` superglobal variable.
// Simple IP fetch $client_ip = $_SERVER['REMOTE_ADDR']; echo 'Client IP Address: ' . $client_ip;
However, in real-world cases where users access your site via proxy servers or CDNs, this method may not give the original IP. To handle that, PHP can also check certain headers:
// IP with proxy handling
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$client_ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$client_ip = $_SERVER['REMOTE_ADDR'];
}
echo 'Client IP Address: ' . $client_ip;
To enhance this, you can use the `getenv()` function, which checks the environment variables set by your web server:
// Using getenv() to get IP
function getUserIP() {
$ip = getenv('HTTP_CLIENT_IP');
if (!$ip) $ip = getenv('HTTP_X_FORWARDED_FOR');
if (!$ip) $ip = getenv('HTTP_X_FORWARDED');
if (!$ip) $ip = getenv('HTTP_FORWARDED_FOR');
if (!$ip) $ip = getenv('HTTP_FORWARDED');
if (!$ip) $ip = getenv('REMOTE_ADDR');
$ip_array = explode(',', $ip);
return trim($ip_array[0]);
}
Call it like this:
$client_ip = getUserIP(); echo 'Client IP Address: ' . $client_ip;
Keep in mind that header values can be spoofed. Use this only for informational or low-security purposes.
