使用filter_var验证具有或不具有协议的 URL
2022-08-30 23:45:59
我正在尝试使用PHP的扩展进行验证。每 http://php.net/manual/en/filter.filters.validate.php:filter_var()
验证值作为 URL(根据 » http://www.faqs.org/rfcs/rfc2396),可选择使用必需的组件。请注意,有效的URL可能没有指定HTTP协议 http:// 因此可能需要进一步的验证来确定URL使用预期的协议,例如 ssh:// 或mailto:。请注意,该函数只会找到有效的ASCII URL;国际化域名(包含非 ASCII 字符)将失败。
关于,请注意有效的URL可能没有指定HTTP协议,我下面的测试表明HTTP协议是必需的()。我如何误解文档?URL 'stackoverflow.com/' is NOT considered valid.
此外,如何阻止诸如 https://https://stackoverflow.com/ 之类的 URL 验证 true?
PS.任何关于我对协议进行消毒的方法的评论将不胜感激。
<?php
function filterURL($url) {
echo("URL '{$url}' is ".(filter_var($url, FILTER_VALIDATE_URL)?'':' NOT ').'considered valid.<br>');
}
function sanitizeURL($url) {
return (strtolower(substr($url,0,7))=='http://' || strtolower(substr($url,0,8))=='https://')?$url:'http://'.$url;
}
filterURL('http://stackoverflow.com/');
filterURL('https://stackoverflow.com/');
filterURL('//stackoverflow.com/');
filterURL('stackoverflow.com/');
filterURL(sanitizeURL('http://stackoverflow.com/'));
filterURL(sanitizeURL('https://stackoverflow.com/'));
filterURL(sanitizeURL('stackoverflow.com/'));
filterURL('https://https://stackoverflow.com/');
?>
输出:
URL 'http://stackoverflow.com/' is considered valid.
URL 'https://stackoverflow.com/' is considered valid.
URL '//stackoverflow.com/' is NOT considered valid.
URL 'stackoverflow.com/' is NOT considered valid.
URL 'http://stackoverflow.com/' is considered valid.
URL 'https://stackoverflow.com/' is considered valid.
URL 'http://stackoverflow.com/' is considered valid.
URL 'https://https://stackoverflow.com/' is considered valid.