FILTER_VALIDATE_URL 是否过于严格? [英] Is FILTER_VALIDATE_URL being too strict?
问题描述
在 PHP 中,filter_var('www.example.com', FILTER_VALIDATE_URL)
返回 false
.这样对吗?www.example.com
不是一个有效的 URL,还是需要在 URL 中明确声明协议(http://、ftp://等)才能正式正确?>
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?
推荐答案
这不是有效的 URL.以 http://
为前缀从来都不是一件对用户非常友好的事情,所以如果你只输入一个域名,现代浏览器就会假设你的意思是 http.软件库确实有点挑剔!
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!
您可以采用的一种方法是通过 parse_url 传递字符串,然后添加任何缺失的元素,例如
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";
}
}
有趣的是,当您使用 FILTER_VALIDATE_URL 时,它实际上在内部使用 parse_url 来确定方案是什么 (查看源代码).感谢 Salathe 在下面的评论中发现这一点.
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.
这篇关于FILTER_VALIDATE_URL 是否过于严格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!