How To Get a User’s IP Address With PHP

In PHP, there are several methods to retrieve a user’s IP address. We will explore two of those ways in this article.

UNLIMITED DOWNLOADS: 500,000+ WordPress & Design Assets

Sign up for Envato Elements and get unlimited downloads starting at only $16.50 per month!

 

The most reliable way to get a user’s IP address in PHP is to use the $_SERVER superglobal variable.

The $_SERVER superglobal variable contains information about the server environment, including the user’s IP address. Here’s an example:

<?php
$ip = $_SERVER['REMOTE_ADDR'];
echo $ip;
?>

The $_SERVER['REMOTE_ADDR'] element returns the IP address of the client (i.e., the user’s device) that is making the request to the server. This method works well for most cases, but there are a few situations where it may not return the correct IP address, such as when the user is behind a proxy server or using a VPN.

To handle these cases, it is recommended to use the following code to get the user’s IP address:

<?php
function get_client_ip() {
    $ip = '';
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$ip = get_client_ip();
echo $ip;
?>

In this code, we first check if the $_SERVER['HTTP_CLIENT_IP'] element is set. If it is, we use its value as the user’s IP address. If not, we then check if the $_SERVER['HTTP_X_FORWARDED_FOR'] element is set. If it is, we use its value as the user’s IP address. If neither of these elements is set, we use the $_SERVER['REMOTE_ADDR'] element as the user’s IP address.

This method provides a more robust solution for retrieving the user’s IP address, as it takes into account the possibility that the user may be behind a proxy server or using a VPN.

Learn more here.