DEV Community

loading...

Get a clients real IP in PHP

Tom Swift
Writer of code - Thinker - #hacktheplanet :D
・1 min read

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

Discussion (2)

Collapse
subzerodev profile image
Subzero-Dev

Thank you for this function!

Collapse
tomthewebcoder profile image
Tom Swift Author

Welcome 🏆😁