Are there any best practices for handling IP address retrieval in PHP, especially for beginners?

When retrieving a user's IP address in PHP, it's important to consider that the IP address can be easily spoofed or manipulated. To get the most accurate IP address, it's recommended to use a combination of $_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_X_FORWARDED_FOR'] headers. This will help you handle cases where the user is behind a proxy server.

$ip = $_SERVER['REMOTE_ADDR'];

if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
    $ip = trim(end($ips));
}

echo $ip;