1

I can't for the life of me figure out how to use filter_var to validate whether a URL is valid when it optionally contains the scheme.

So for example, I would like both https://www.google.com and www.google.com to pass validation from filter_var.

I've tried using the FILTER_FLAG_HOST_REQUIRED flag exclusively: filter_var("www.google.com", FILTER_VALIDATE_URL, ['flags' => FILTER_FLAG_HOST_REQUIRED])

and also by negating FILTER_FLAG_SCHEME_REQUIRED with FILTER_FLAG_HOST_REQUIRED: filter_var("www.google.com", FILTER_VALIDATE_URL, ~FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED)

and with just negating FILTER_FLAG_SCHEME_REQUIRED: filter_var("www.google.com", FILTER_VALIDATE_URL, ~FILTER_FLAG_SCHEME_REQUIRED)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Jimmy P
  • 1,790
  • 4
  • 17
  • 32
  • I'd like to avoid a regex and `filter_var` returns false by default when you don't include the scheme: `filter_var("www.google.com", FILTER_VALIDATE_URL)`. None of the answers in that post help me. – Jimmy P Jun 06 '17 at 21:18
  • curl it and check the response. – Matt Jun 06 '17 at 21:20
  • 1
    Or just prefix with `http` if required. – u_mulder Jun 06 '17 at 21:22
  • @mkaatman Curl will only determine if the URL exists currently. I don't care if the URL exists; I just want to know if its formatting is valid. – Jimmy P Jun 06 '17 at 21:43
  • @u_mulder That would require validating the same URL twice with only one minor difference. From my understanding `filter_var` has the ability to do what I'm asking in a single function call. – Jimmy P Jun 06 '17 at 21:44
  • I can't find a way to unset flags, and since SCHEME validation is on by default since 5.2.1 .... I would do this some other way. Like as suggested above – Lightness Races in Orbit Jun 06 '17 at 21:46
  • Should it also pass querystring params? `http://example.com?foo=bar` – Matt Jun 06 '17 at 22:14
  • @mkaatman Optionally – Jimmy P Jun 06 '17 at 22:17

0 Answers0