Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anything start with http:// is validated by FILTER_VALIDATE_URL?

I tested with strings and int that I can imagine, as long as it start with http://, it will be a valid url using FILTER_VALIDATE_URL. So, why we need FILTER_VALIDATE_URL? Why not just add http:// on an input whenever we want to make it valid?

var_dump(filter_var ('http://example',FILTER_VALIDATE_URL ));
like image 211
Jenny Avatar asked Aug 29 '12 02:08

Jenny


1 Answers

Well technically, any URI that starts with a scheme (like http://) and contains valid URI characters after that is valid as per the official URI specification in RFC 3986:

Each URI begins with a scheme name, as defined in Section 3.1, that refers to a specification for assigning identifiers within that scheme. As such, the URI syntax is a federated and extensible naming system wherein each scheme's specification may further restrict the syntax and semantics of identifiers using that scheme.

So there's nothing strange about the return you're getting -- that's what's supposed to happen. As to why you should use the filter_var with the FILTER_VALIDATE_URL flag ... it's way more semantically appropriate than doing something like the following for every possible URL scheme, wouldn't you agree?

if (strpos($url, 'http://') === 0
    || strpos($url, 'ftp://') === 0
    || strpos($url, 'telnet://') === 0
) {
    // it's a valid URL!
}
like image 160
rdlowrey Avatar answered Oct 20 '22 13:10

rdlowrey