Anything start with http:// is validated by FILTER

2019-01-28 02:09发布

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 ));

1条回答
Explosion°爆炸
2楼-- · 2019-01-28 02:31

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!
}
查看更多
登录 后发表回答