tor
tor

Reputation: 191

PHP - Get REAL ipaddress

This is the function I use to get the client ip:

function get_client_ip_server() {
$ipaddress = '';
if ($_SERVER['HTTP_CLIENT_IP'])
    $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if($_SERVER['HTTP_X_FORWARDED_FOR'])
    $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if($_SERVER['HTTP_X_FORWARDED'])
    $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if($_SERVER['HTTP_FORWARDED_FOR'])
    $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if($_SERVER['HTTP_FORWARDED'])
    $ipaddress = $_SERVER['HTTP_FORWARDED'];
else if($_SERVER['REMOTE_ADDR'])
    $ipaddress = $_SERVER['REMOTE_ADDR'];
else
    $ipaddress = 'UNKNOWN';

return $ipaddress;
}

The only problem is that I get a error in PHP: Notice: Undefined index: HTTP_CLIENT_IP

And in the other variables too. Question: How should I fix this and WHY does it work for others?

Upvotes: 0

Views: 2033

Answers (4)

twincamspit
twincamspit

Reputation: 1

Or you can use '@' to stop the warning/error if it's unset or null, for example:

if (@$_SERVER['HTTP_CLIENT_IP'] != '') 
    $ipaddress = $_SERVER['HTTP_CLIENT_IP'];

Upvotes: 0

Abelardo Bejarano
Abelardo Bejarano

Reputation: 11

try this

 $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
            $ipaddress =getenv('HTTP_CLIENT_IP');
        else if(getenv('HTTP_X_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
        else if(getenv('HTTP_X_FORWARDED'))
            $ipaddress = getenv('HTTP_X_FORWARDED');
        else if(getenv('HTTP_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
        else if(getenv('HTTP_FORWARDED'))
            $ipaddress = getenv('HTTP_FORWARDED');
        else if(getenv('REMOTE_ADDR'))
            $ipaddress = getenv('REMOTE_ADDR');
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;

Upvotes: 1

unixmiah
unixmiah

Reputation: 3143

try this

$http_client_ip = $_SERVER['HTTP_CLIENT_IP'];

if (!empty($http_client_ip)) {
$ip_address = $http_client_ip;  

Upvotes: 0

slapyo
slapyo

Reputation: 2991

Use isset on all the checks.

function get_client_ip_server() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
    $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
    $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
    $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
    $ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
    $ipaddress = $_SERVER['REMOTE_ADDR'];
else
    $ipaddress = 'UNKNOWN';

return $ipaddress;
}

Upvotes: 2

Related Questions