How can PHP developers output an IPv4 address like "192.168.0.1" instead of "::1" when using $_SERVER["REMOTE_ADDR"]?

When using $_SERVER["REMOTE_ADDR"] in PHP, the result may sometimes be "::1" which is the IPv6 loopback address for localhost. To output an IPv4 address like "192.168.0.1" instead, you can check if the result is an IPv6 address and convert it to an IPv4 address using the inet_ntop and inet_pton functions.

$remote_addr = $_SERVER["REMOTE_ADDR"];

if (filter_var($remote_addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
    $ipv4_mapped = substr($remote_addr, strrpos($remote_addr, ':') + 1);
    $ipv4_address = inet_ntop(inet_pton($ipv4_mapped));
    echo $ipv4_address;
} else {
    echo $remote_addr;
}