To ensure that you only get the client's IPv4 address in PHP, you can use a combination of $_SERVER superglobal and a check for valid IPv4 addresses.
function getClientIPv4() {
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach ($ipList as $ip) {
$ip = trim($ip);
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return $ip;
}
}
}
// Fallback to the remote address if no forwarded IP is valid
if (!empty($_SERVER['REMOTE_ADDR']) && filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return $_SERVER['REMOTE_ADDR'];
}
return null;
}
// Usage
$clientIPv4 = getClientIPv4();
if ($clientIPv4) {
echo "Client's IPv4: " . $clientIPv4;
} else {
echo "No valid IPv4 found.";
}
This function will check for IPv4 addresses in both the HTTP_X_FORWARDED_FOR and REMOTE_ADDR fields, ensuring you only get valid IPv4 addresses. If no valid IPv4 is found, it will return null.