Getting the client IP address
Tuesday, 5 June 2007
We’ve seen plenty of PHP scripts that rely on the $_SERVER['REMOTE_ADDR'] variable when trying to establish the IP address of the client computer. The problem with this approach is that if your visitor is behind a corporate firewall or proxy, then the above will actually be the IP of the firewall or proxy, not the visitors computer.
This function pretty much caters for all situations:
function getip() {
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
$result = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
$result = $_SERVER['HTTP_CLIENT_IP'];
} else {
$result = $_SERVER['REMOTE_ADDR'];
}
if (strstr($result, ',')) {
$result = strtok($result, ',');
}
return $result;
}
Just keep in mind that $_SERVER['REMOTE_ADDR'] can be (and has been) spoofed.
|
Hi,
We are in the requirement that we need to get the IP address (local machine's). We are getting the general IP address of the provider and not the network inside it. Meaning we are getting the same IP address in all machines in our office. As per the suggestion given by you in this site, we have tried your example, but still we are getting the same as IP address. Can we get suggestions over it?
Regards, Guru