0

I am almost banging my head....

I searched a lot here and in google... but I am not sure I am doing things right.

here is my code:

if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
{
  $ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
{
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
  $ip=$_SERVER['REMOTE_ADDR'];
}

$country= file_get_contents("http://ipinfo.io/$ip/json");
echo ($ip.'---'.$country);

The problem is when I run this code (Not on localhost, but on my server)... I see some ip like 10.100.x.x.

and country I get is empty.

but when I visit http://ipinfo.io/, I see some different IP for me. It is something like 182.183.x.x and I can see my country and city information correctly.

I tried some other IP locators as well and All say my IP address is 182.183.x.x. I tried to locate 10.100.x.x. as well.. All services returned with empty country.

So how can I obtain my real IP in php?? What am I doing wrong?

MJ Khan
  • 1,696
  • 3
  • 21
  • 36

1 Answers1

4

182.183.x.x is an IP on the Internet.

10.100.x.x is a private address range. The request, to your server, is coming from a computer on the server's LAN.

Either:

  • Your server is on the same local network as your development environment, in which case this is normal (the server sees the IP address of your workstation, but the third party website sees the IP address of your router) and nothing to worry about or
  • Your server is hosted behind a proxy (possibly for load balancing or caching) and it is failing to set the HTTP_X_FORWARDED_FOR header. You would need to look at your hosting service's network configuration to deal with this.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    He's right. It sounds like you're using a virtual hosting like AWS, Azure, etc. You can see more about how to fix your IP problem at http://forum.piwik.org/read.php?2,71051,84063 – Machavity May 16 '14 at 14:39
  • You explain the why, but offer no answers. This seems like an answer that would be better placed as a comment. – Ryan May 16 '14 at 14:40
  • Ah... I just remember the server is behind some load balancer.. Thanks Quentin... – MJ Khan May 16 '14 at 14:49