DEV Community

Tom Swift
Tom Swift

Posted on

3 3

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.

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay