How can we get IP address of a client in PHP?

$_SERVER[“REMOTE_ADDR“];

In PHP, you can retrieve the IP address of a client using the $_SERVER superglobal array. The IP address of the client can be found in the REMOTE_ADDR key of the $_SERVER array. Here’s a simple example:

php
<?php
// Get the client's IP address
$ipAddress = $_SERVER['REMOTE_ADDR'];

echo "Client's IP Address: " . $ipAddress;
?>

However, it’s important to note that REMOTE_ADDR may not always provide the actual IP address of the client due to various reasons like the client being behind a proxy server or using a VPN. In such cases, you may need to consider additional headers such as HTTP_X_FORWARDED_FOR or HTTP_CLIENT_IP to get the correct IP address. Here’s an example:

php
<?php
// Function to get the client IP address
function getClientIp() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}

// Get the client's IP address
$ipAddress = getClientIp();

echo "Client's IP Address: " . $ipAddress;
?>

This function attempts to retrieve the client’s IP address from various headers where it might be present. However, it’s worth noting that relying solely on client-supplied information may not always be accurate or secure, so use it with caution.