Wednesday, February 9, 2011

Why is getenv('REMOTE_ADDR') giving me a blank IP address?

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.

  • Why don't you use

    $_SERVER['REMOTE_ADDR']
    

    and

    $_SERVER['HTTP_X_FORWARDED_FOR']
    
  • on php.net it says the follwing:

    The function 'getenv' does not work if your Server API is ASAPI (IIS). So, try to don't use getenv('REMOTE_ADDR'), but $_SERVER["REMOTE_ADDR"].

    Did you maybe try to do it with $_SERVER?

    From fly.floh
  • 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.

  • 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 ;-)

    From easyDaMan

0 comments:

Post a Comment