What are the potential challenges or limitations when trying to retrieve the correct IP address in PHP?

One potential challenge when trying to retrieve the correct IP address in PHP is that the server may be behind a proxy or load balancer, which can result in the wrong IP address being returned. To solve this, you can check for specific server variables that may contain the correct IP address.

// Check for specific server variables to retrieve the correct IP address
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

echo $ip;