phpurlphp-7filter-var

filter_var($url, FILTER_FLAG_HOST_REQUIRED) always returning false


filter_var($url, FILTER_FLAG_HOST_REQUIRED) is always returning false. Below is my code, I can't figure out why it is false on all urls.

$url = $this->input('website'); //form input

if ( $parts = parse_url($url) ) {
    if ( !isset($parts["scheme"]) )
        {
            $url = "https://$url";
        }
}

if (!filter_var($url, FILTER_FLAG_HOST_REQUIRED)) {
    dd('not valid  '.$url);
}
else {
    dd('valid  '.$url);
}

if I enter 'www.cnn.com' in the form, the following is the result:

not valid https://www.cnn.com

Solution

  • The second parameter to filter_var must be one of the primary filters; FILTER_FLAG_HOST_REQUIRED is not a filter, it's an option flag for the FILTER_VALIDATE_URL filter. So:

    filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)