Why is getenv('REMOTE_ADDR') giving me a blank IP address?
-
05-07-2019 - |
Question
This PHP code...
207 if (getenv(HTTP_X_FORWARDED_FOR)) {
208 $ip = getenv('HTTP_X_FORWARD_FOR');
209 $host = gethostbyaddr($ip);
210 } else {
211 $ip = getenv('REMOTE_ADDR');
212 $host = gethostbyaddr($ip);
213 }
Throws this warning...
Warning: gethostbyaddr() [function.gethostbyaddr]: Address is not in a.b.c.d form in C:\inetpub...\filename.php on line 212
It seems that $ip is blank.
Solution
on php.net it says the following:
The function
getenv
does not work if your Server API is ASAPI (IIS). So, try to don't usegetenv('REMOTE_ADDR')
, but$_SERVER["REMOTE_ADDR"]
.
Did you maybe try to do it with $_SERVER
?
OTHER TIPS
Why don't you use
$_SERVER['REMOTE_ADDR']
and
$_SERVER['HTTP_X_FORWARDED_FOR']
A better solution has already been given. But still:
getenv('HTTP_X_FORWARD_FOR');
should be
getenv('HTTP_X_FORWARDED_FOR');
Yeah... sometimes computers want to have strings they understand ;-)
First of all, getenv() takes a string as parameter. On line 207, you should use:
getenv('HTTP_X_FORWARDED_FOR')
...instead of:
getenv(HTTP_X_FORWARDED_FOR)
Secondly, accessing these variables through $_SERVER is a more reliable solution, as getenv() tends to display different behaviour on different platforms.
Also, these variables will probably not work if you are running this script through CLI.
Try a var_dump($ip); and see what the variable contains.