if your PHP script is behind a proxy or load balancer, you might need to use additional headers such as HTTP_X_FORWARDED_FOR
to get the true client IP address. Here’s a modified version of the code to handle this scenario:
<?php
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip_address = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip_address = $_SERVER['REMOTE_ADDR'];
}
echo "Your IP Address is: " . $ip_address;
?>
This version checks if the HTTP_CLIENT_IP
or HTTP_X_FORWARDED_FOR
headers are present and uses them to determine the client’s IP address. If neither header is available, it falls back to REMOTE_ADDR
.