DEV Community

Tom Swift
Tom Swift

Posted on

Get a clients real IP in PHP

Here's a simple php function to get the real IP of a client - Utilizing it inside a function so as to avoid duplicate code.

I use this function on most of my projects and have found it very reliable when dealing with getting the users real IP.

Enjoy :)

function GetClientIP()
{
    $ClientIPArr = array(
        "HTTP_CLIENT_IP",
        "HTTP_CF_CONNECTING_IP",
        "HTTP_X_FORWARDED",
        "HTTP_X_FORWARDED_FOR",
        "HTTP_FORWARDED_FOR",
        "REMOTE_ADDR"
    );
    $found = 0;
    foreach ($ClientIPArr as $value)
    {
        if (isset($_SERVER[$value]))
        {
            if (filter_var($_SERVER[$value], FILTER_VALIDATE_IP)) {
            $ClientIP = $_SERVER[$value];
            $found++;
            break;
            }
        }
    }
    if ($found > 0)
    {
        return $ClientIP;
    }
    else
    {
        return 'Not Found';
    }
}
echo GetClientIP();

Top comments (2)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.