Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

get ip address

Status
Not open for further replies.

kurie

Programmer
Jun 4, 2008
170
0
0
ZA
I would like to get IP addresses for website visitors, and im using the following function. My problem it doesnt get the real ip address of the sending machine, looks like its picking a gateway, does anyone whats wrong with my code
function getIP()
{
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'];
}
return $ip;
}
 
This function has always worked for me:
Code:
function getIpAddress()
{
  if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip_expl = explode('.', $_SERVER['HTTP_CLIENT_IP']);
    $referer = explode('.', $_SERVER['REMOTE_ADDR']);
    if ($referer[0] != $ip_expl[0]) {
      $ip = array_reverse($ip_expl);
      return implode('.', $ip);
    }
    else {
      return $_SERVER['HTTP_CLIENT_IP'];
    }
  }
  else {
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      if (strstr($_SERVER['HTTP_X_FORWARDED_FOR'], ',')) {
        $ip_expl = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return end($ip_expl);
      }
      else {
        return $_SERVER['HTTP_FORWARDED_FOR'];
      }
    }
    else {
      return $_SERVER['REMOTE_ADDR'];
    }
  }

  return FALSE;
}
 
hi thanks for your response,

unfortunately its still returning 127.0.0.1 as the IP address not my real IP Address.

Regards
 
If you are accessing the site from the webserver, it will always report 127.0.0.1 as that is the reserved address for the localhost/loop-back interface. Try going to it from a different computer to get a different result.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top