Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is FILTER_VALIDATE_URL being too strict?

Tags:

url

php

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?

like image 477
federico-t Avatar asked Mar 21 '12 07:03

federico-t


2 Answers

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.

like image 70
Paul Dixon Avatar answered Nov 09 '22 08:11

Paul Dixon


The URL have to correspond with the rules set forward in RFC 2396, and according to that spec the protocol is necessary.

like image 26
Christofer Eliasson Avatar answered Nov 09 '22 08:11

Christofer Eliasson