3

$_SERVER['REMOTE_ADDR'] returns 127.0.0.1.

is that because I installed varnish cache and data goes to varnish, then apache, and server think request came from varnish not client?

Charles
  • 50,943
  • 13
  • 104
  • 142
bazinga
  • 881
  • 2
  • 7
  • 13
  • I don't know about Varnish but that might be the case.. I had this problem when using nginx as a load balancer.. just print_r the $_SERVER superglobal.. you will find the IP in a different field..like X_FORWARDED_FOR – mishu Oct 11 '13 at 06:00

2 Answers2

17

Get the remote ip address like this:

public function getRemoteIPAddress() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];

    } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    return $_SERVER['REMOTE_ADDR'];
}
vvns
  • 3,548
  • 3
  • 41
  • 57
  • 1
    Sorry for downvote, but this is bad advice. See [@Ka.'s answer](http://stackoverflow.com/a/37254156/2032498). Also, `HTTP_CLIENT_IP` can come from the client and is therefore unreliable. In general, first make sure that `REMOTE_ADDR` is a trusted host. And only then you can rely on further HTTP headers like `X_FORWARDED_FOR`. – Kontrollfreak Apr 02 '17 at 16:54
  • https://stackoverflow.com/a/28217316/2343242 has code to just grab the first ip address listed by `HTTP_X_FORWARDED_FOR` – ryanrain Jun 04 '19 at 16:55
3

Beware, $_SERVER['HTTP_X_FORWARDED_FOR'] can contain multiple ips, see How do I get the correct IP from HTTP_X_FORWARDED_FOR if it contains multiple IP Addresses?

Community
  • 1
  • 1
Ka.
  • 1,189
  • 1
  • 12
  • 18