What is use of FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED flags for FILTER_VALIDATE_URL?

Viewed 12979

We can use filter_vars() with FILTER_VALIDATE_URL and flags:

FILTER_FLAG_SCHEME_REQUIRED
FILTER_FLAG_HOST_REQUIRED
FILTER_FLAG_PATH_REQUIRED
FILTER_FLAG_QUERY_REQUIRED

FILTER_VALIDATE_URL validates value as URL according to RFC 2396 and internally use parse_url() and require scheme (protocol) and host parts.

If I want check path and query parts aswell I can use filter_vars like this:

filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED | FILTER_FLAG_QUERY_REQUIRED);

But what is use of FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED flags? It seems like no matter whether we specify these flags or not scheme and host parts will be checked anyway.

For example, filtering valid relative URL like this:

filter_var('test1/2.html', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED);

return false.

2 Answers

The flags FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED have not had any effect since 5.2.1 in that they are always on, there is no way to disable them, and they're not actually used anywhere in the PHP source.

https://bugs.php.net/bug.php?id=75442

The docs have just been clarified regarding the use of the constants, but they're not likely to be removed until the next major PHP release [eg: PHP8] for the sake of preserving backwards-compatibility.

There are a narrow set of hard-coded schemes that don't require a hostname portion, [mailto:, news:, and file:] but if you want to implement validation of other URLs that do not have host or scheme parts you'll need to write something that calls parse_url() and operates on its return.

You can have a peek at the current URL validation source here: https://github.com/php/php-src/blob/master/ext/filter/logical_filters.c#L517-L574

Related