-3

I'm building a website with PHP and I want to configure it to only check the client's IPv4, but I'm having a problem that if the client has IPv6, it gets IPv6.

I get the IP with $_SERVER['HTTP_X_FORWARDED_FOR'] but only get 1 single IP and prioritize getting IPv6. I want to only receive IPv4 in Apache by Listening to 0.0.0.0:80 but it doesn't work. Please give me a solution

2
  • 1
    If you don't want to get ipv6 connections then you must stop listening to ipv6 Commented Oct 30, 2024 at 11:20
  • I tried but don't know how to bypass ipv6 Commented Oct 31, 2024 at 1:59

1 Answer 1

-2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your function will just return null. Which makes it useless
I use it like that but only receive 1 ip from the client, but it prioritizes sending ipv6

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.