How to get client real ip address in php?

by mallory_cormier , in category: PHP General , a year ago

How to get client real ip address in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by orpha , a year ago

@mallory_cormier 

To get the client's real IP address in PHP, you can use the $_SERVER superglobal variable to retrieve the REMOTE_ADDR value. However, there are some cases where this may not always give you the correct IP address, such as when the client is behind a proxy or load balancer. In such cases, you can look for additional headers like HTTP_X_FORWARDED_FOR or HTTP_CLIENT_IP to get the client's real IP address. Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function getClientIP() {
    $ip = $_SERVER['REMOTE_ADDR'];
    
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    
    return $ip;
}

// Usage
$ipAddress = getClientIP();
echo "Client IP Address: " . $ipAddress;


Note that the order in which you check the headers may vary depending on your server configuration.

by lindsey.homenick , a year ago

@mallory_cormier 

It is important to note that the client can s**** their IP address or use a VPN to hide their real IP address. So, while this method might work in most cases, it is not foolproof for identifying the client's real IP address.