How To Get Client IP Address In PHP

When we develop a web application, then sometimes we need to store the IP address of the client to maintain security and validations.

Getting the visitors IP also helps to track his activity on the website.

It is very easy to get the client IP address in PHP. We use $_SERVER array to get the user IP address. REMOTE_ADDR easily gives you client IP address.

$_SERVER[‘REMOTE_ADDR’] gives user IP address in PHP.

Let’s see how to get

Getting Client IP Address

echo "Client IP: $_SERVER['REMOTE_ADDR']";
But sometimes this approach will not give you actual IP address of client due to proxy used by client. In this case we have to follow different approach.
function get_client_ip() {

    $client_ip = "";

    //client is using a shared ip:
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $client_ip = $_SERVER['HTTP_CLIENT_IP'];

    // client is using a proxy server.
    else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];


    elseif (isset($_SERVER['REMOTE_ADDR']))
        $client_ip = $_SERVER['REMOTE_ADDR'];
    else
        $client_ip = "Unknown";

    return $client_ip;
}

echo "Your IP is: " . get_client_ip();

We can also use getenv instead of $_SERVER to get user IP address in PHP. To get client IP address just echo above function. That’s it.

In this tutorial you have learned about Get IP Address using PHP. If you have any query regarding this article, please feel free to comment.

1 thought on “How To Get Client IP Address In PHP”

Leave a Comment