Is there any way to validate IPv6 URLs?
http://[2001:630:181:35::83]/index.php
should be a valid URL
but PHP's filter_var
function will return false
How can I add support for IPv6 addresses?
Is there any way to validate IPv6 URLs?
http://[2001:630:181:35::83]/index.php
should be a valid URL
but PHP's filter_var
function will return false
How can I add support for IPv6 addresses?
I made a workaround using a combination of FILTER_VALIDATE_URL and FILTER_VALIDATE_IP with FILTER_FLAG_IPV6. This is a regex free solution:
function validate($url)
{
# 1. We validate the url
if (false === filter_var($url, FILTER_VALIDATE_URL)) {
# 2. Consider the posibility of an IPV6 host
$host = parse_url($url, PHP_URL_HOST);
$ipv6 = trim($host, '[]'); // trim potential enclosing tags for IPV6
# 3. Validate IPV6
if (false === filter_var($ipv6, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return false;
} else {
# 4. We have a valid IPV6, replace it with a generic host url for further validation purposes
$newUrl = str_replace($host, 'www.someUrl.com', $url);
# 5. We validate the new url
if (false === filter_var($newUrl, FILTER_VALIDATE_URL)) {
return false;
}
}
}
return true;
}
NOTE: parse_url() doesn't always fail if the url is not valid, therefore you can't replace the host blindly, prior to validation, you might miss something wrong in the host itself. So... validating a second time after changing the host seems to be the right way to do it in case of IPV6.