Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to get user ip address [duplicate]

Tags:

php

Possible Duplicate:
What is the most accurate way to retrieve a user's correct IP address in PHP?

Is there any better function in php to get user ip address? this is what i use at the moment

function GetIP()
{
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "unknown";
return($ip);
}
like image 759
Frank Nwoko Avatar asked Jul 16 '11 14:07

Frank Nwoko


1 Answers

Adapted from this answer:

function GetIP()
{
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
    {
        if (array_key_exists($key, $_SERVER) === true)
        {
            foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip)
            {
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
                {
                    return $ip;
                }
            }
        }
    }
}

Checks for IPs (in order) in:

  1. HTTP_CLIENT_IP
  2. HTTP_X_FORWARDED_FOR
  3. HTTP_X_FORWARDED
  4. HTTP_X_CLUSTER_CLIENT_IP
  5. HTTP_FORWARDED_FOR
  6. HTTP_FORWARDED
  7. REMOTE_ADDR

Remember that the only IP address you can trust is the one coming from $_SERVER['REMOTE_ADDR'].

like image 50
Alix Axel Avatar answered Oct 10 '22 08:10

Alix Axel