PHP filter_var() - FILTER_VALIDATE_URL

耗尽温柔 提交于 2019-11-29 10:45:59

The parsing starts here:
http://svn.php.net/viewvc/php/php-src/trunk/ext/filter/logical_filters.c?view=markup

and is actually done in /trunk/ext/standard/url.c

At a first glance I can't see anything that purposely rejects non-ASCII characters, so it's probably just lack of unicode support. PHP is not good in handling non-ASCII characters anywhere. :(

Technically that is not a valid URL according to section 5 of RFC 1738. Browsers will automatically encode the ã character to %C3%A3 before sending the request to the server. The technically valid full url here is: http://pt.wikipedia.org/wiki/Guimar%C3%A3es Pass that to the VALIDATE_URL filter and it will work fine. The filter only validates according to spec, it doesn't try to fix/encode characters for you.

The following code uses filter_var but encode non ascii chars before calling it. Hope this helps someone.

<?php

function validate_url($url) {
    $path = parse_url($url, PHP_URL_PATH);
    $encoded_path = array_map('urlencode', explode('/', $path));
    $url = str_replace($path, implode('/', $encoded_path), $url);

    return filter_var($url, FILTER_VALIDATE_URL) ? true : false;
}

// example
if(!validate_url("http://somedomain.com/some/path/file1.jpg")) {
    echo "NOT A URL";
}
else {
    echo "IS A URL";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!