How can PHP developers ensure accurate IP address detection for both local and remote access scenarios?

To ensure accurate IP address detection for both local and remote access scenarios in PHP, developers can use the $_SERVER['REMOTE_ADDR'] variable to get the IP address of the client accessing the server. However, in some cases, this variable may not always return the correct IP address, especially when the client is behind a proxy or load balancer. To account for this, developers can check additional server variables like HTTP_X_FORWARDED_FOR to accurately determine the client's IP address.

// Get the client's 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 "Client's IP address: " . $ip;