phpurl-validation

PHP check if url is valid


I wonder what would be the best way in php to check if provided url is valid... At first I tried with:

filter_var($url, FILTER_VALIDATE_URL) === false

But it does not accept www.example.com (without protocol). So I tried with a simple modification:

protected function checkReferrerUrl($url) {
    if(strpos($url, '://') == false) {
        $url = "http://".$url;
    }
    if(filter_var($url, FILTER_VALIDATE_URL) === false) {
        return false;
    }
    return true;
}

Now it works fine with www.example.com but also accepts simple foo as it converts to http://foo. However though this is not a valid public url I think... so what would you suggest? Go back to traditional regexp?


Solution

  • I recommend, that you do not use filter_var with type URL. There are much more side-effects. For example, these are valid URLs according to filter_var:

    http://example.com/"><script>alert(document.cookie)</script>
    http://example.ee/sdsf"f
    

    Additionally FILTER_VALIDATE_URL does not support internationalized domain names (IDN).

    I recommend using a regex combined with some ifs afterwards (f.e. for the domain) for security reasons. Without the security aspect I am using parse_url to take my parts. But this function has a similar issue, when the scheme (no http/https) is missing.