php - filter_var returns false 即使使用 urlencode

php - filter_var returns false even with urlencode

$url="http://www.example.com/日本語/こんにちは.html";
$result=filter_var(urlencode($url), FILTER_VALIDATE_URL);

我正在编码URL!那么,为什么是$returnfalse

因为它不是有效的 URL 大概:

http://php.net/manual/de/filter.filters.validate.php

来自文档:

Validates value as URL (according to » http://www.faqs.org/rfcs/rfc2396), optionally with required components. Beware a valid URL may not specify the HTTP protocol http:// so further validation may be required to determine the URL uses an expected protocol, e.g. ssh:// or mailto:. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.

URL 编码的 URLs 总是失败,因为 urlencode 将无效字符添加到 URL。此函数不适用于使用中文字符验证 URLs。

特别是最后几行说得很准确:注意 函数只会发现 ASCII URLs 是有效的;国际化 域名(包含非 ASCII 字符)将失败。

编辑:@jeroen 是对的,顺便说一句 urlencode() 用于编码参数而不是整个 url。

您使用 urlencode 对查询参数值进行编码。它对 url 中具有特殊含义的字符进行编码,例如 :/?

如果您编码整个 url - 而不是查询部分中的值 - 它不再是有效的 url。

这是编码后的 url:

http%3A%2F%2Fwww.example.com%2F%E6%97%A5%E6%9C%AC%E8%AA%9E%2F%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF.html