problem with $_SERVER['REMOTE_ADDR']

22,054

Solution 1

You should query for HTTP_X_FORWARDED_FOR first and if it isn't assigned use REMOTE_ADDR.

Solution 2

@James @imez

By default the client IP is in $_SERVER['REMOTE_ADDR']. When the user enters your site using a PROXY server (HTTP gateway) it tells you who it's proxing for (HTTP_X_FORWARDED_FOR) and will give it's own Proxy IP in $_SERVER['REMOTE_ADDR'].

Anonymous proxies will omit HTTP_X_FORWARDED_FOR or simply lie to you.

Knowing you have a real client IP isn't possible.

Solution 3

I have to mention that the array key is case-sensitive, and should be upper-case:

var_dump($_SERVER['remote_addr']);
echo "\n";
var_dump($_SERVER['REMOTE_ADDR']);

Output:

Notice: Undefined index: remote_addr in /home/adam/public_html/2011/01/04/foo.php on line 3
NULL

string(15) "10.0.1.51"

I would var_dump($_SERVER) just to evaluate the state of your world, and go from there.

Share:
22,054
imez
Author by

imez

Updated on July 09, 2022

Comments

  • imez
    imez almost 2 years

    i used $_SERVER['REMOTE_ADDR'] and it returns client ip address (IP address from which the user is viewing the current page) but at now (and same code) it returns host ip address (i checked ip address with ip location). problem is with host or what? thank u.

    • TJHeuvel
      TJHeuvel over 13 years
      You wouldnt be visiting it from your host by coincidence?
    • Gumbo
      Gumbo over 13 years
      Do you use some kind of proxy?
    • imez
      imez over 13 years
      no. i checked several times. i dont use proxy
    • Rosh Oxymoron
      Rosh Oxymoron over 13 years
      Gumbo meant a proxy on the server side, not on the client side (something like a httpd accelerator).
  • imez
    imez over 13 years
    i use HTTP_X_FORWARDED_FOR at now and it returns correct ip. but why problem with REMOTE_ADDR?
  • Rosh Oxymoron
    Rosh Oxymoron over 13 years
    Because there is a proxy between you and the server, and you get the address of the proxy as REMOTE_ADDR. HTTP_X_FORWARDED_FOR is the IP of the client using the proxy.
  • James
    James over 13 years
    @imez: As @Rosh has already pointed out there must be a proxy between you and the server and if you query REMOTE_ADDR you will get the IP of the proxy server. If you check for HTTP_X_FORWARDED_FOR first then a lot of the time the proxy will populate this with the real IP address.
  • James
    James over 13 years
    I have stated that in my comment on my answer. It's never a guarentee that the real IP address is in HTTP_X_FORWARDED_FOR but like I said, most of the time it is.
  • ChrisV
    ChrisV over 11 years
    Dumping the whole of $_SERVER is a good idea - I discovered the real IP address behind a proxy I'm working with in HTTP_CLIENT_IP that way...
  • Oki Erie Rinaldi
    Oki Erie Rinaldi over 7 years
    what if it happens on localhost? how do i know i use proxy (that surely i don't use)?