problem with $_SERVER['REMOTE_ADDR']
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.
imez
Updated on July 09, 2022Comments
-
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 over 13 yearsYou wouldnt be visiting it from your host by coincidence?
-
Gumbo over 13 yearsDo you use some kind of proxy?
-
imez over 13 yearsno. i checked several times. i dont use proxy
-
Rosh Oxymoron over 13 yearsGumbo meant a proxy on the server side, not on the client side (something like a httpd accelerator).
-
-
imez over 13 yearsi use HTTP_X_FORWARDED_FOR at now and it returns correct ip. but why problem with REMOTE_ADDR?
-
Rosh Oxymoron over 13 yearsBecause 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 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 forHTTP_X_FORWARDED_FOR
first then a lot of the time the proxy will populate this with thereal
IP address. -
James over 13 yearsI 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 over 11 yearsDumping 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 over 7 yearswhat if it happens on localhost? how do i know i use proxy (that surely i don't use)?