Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notice: Undefined index: HTTP_X_FORWARDED_FOR Error in Function

Tags:

php

I'm getting Notice: Undefined index: HTTP_X_FORWARDED_FOR in the Function below:

function _ip( )
{
    return ( preg_match( "/^([d]{1,3}).([d]{1,3}).([d]{1,3}).([d]{1,3})$/", $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'] );
}
like image 333
Satch3000 Avatar asked Mar 03 '12 18:03

Satch3000


1 Answers

You should be using the getenv() method instead of $_SERVER.

function _ip( )
{
    if (preg_match( "/^([d]{1,3}).([d]{1,3}).([d]{1,3}).([d]{1,3})$/", getenv('HTTP_X_FORWARDED_FOR'))
    {
        return getenv('HTTP_X_FORWARDED_FOR');
    }
    return getenv('REMOTE_ADDR');
}

Also, I would stick with just $ip = getenv('REMOTE_ADDR') as spammers can set the HTTP_X_FORWARDED_FOR header themselves to anything they want while they can't change the remote_addr. The problem is that "good" proxies tell the truth about HTTP_X_FORWARDED_FOR so you would miss that.

like image 184
Xeoncross Avatar answered Sep 30 '22 01:09

Xeoncross