In PHP, filter_var('www.example.com', FILTER_VALIDATE_URL)
returns false
. Is this correct? Isn't www.example.com
a valid URL, or protocols (http://, ftp://, etc.) need to be explicitly stated in the URL to be formally correct?
It's not a valid URL. Prefixing things with http://
was never a very user-friendly thing, so modern browsers assume you mean http if you just enter a domain name. Software libraries are, rightly, a little bit more picky!
One approach you could take is passing the string through parse_url, and then adding any elements which are missing, e.g.
if ( $parts = parse_url($url) ) {
if ( !isset($parts["scheme"]) )
{
$url = "http://$url";
}
}
Interestingly, when you use FILTER_VALIDATE_URL, it actually uses parse_url internally to figure out what the scheme is (view source). Thanks to salathe for spotting this in the comments below.
The URL have to correspond with the rules set forward in RFC 2396, and according to that spec the protocol is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With