1

I've been trying to use FILTER_VALIDATE_URL, as well as regex, to validate url, but no luck.

For example:

$url = "http://www.stackoverflow";

    if (preg_match("/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/", $url)) {
      echo "URL is valid";
    }
    else {
      echo "URL is invalid";
    }
        echo("$url is not a valid URL");
    }

The above will show valid url, even if domain extension is omitted, the same goes for FILTER_VALIDATE_URL

What I would like is to validate url only if entered in following format:

http://www.stackoverflow.com
https://www.stackoverflow.com
http://stackoverflow.com
https://stackoverflow.com

anything like:

http://stackoverflow
https://stackoverflow
http://www.stackoverflow
https://www.stackoverflow

should be invalid.

And of course it should work with any type of domain extension.

Alko
  • 1,421
  • 5
  • 25
  • 51
  • Did you tried something more? It's the code working now? If yes, mark the question as resolved, and if the answer helps you, upvote ;) – JP. Aulet Sep 15 '17 at 09:28

1 Answers1

1

If you want to work with FILTER_VALIDATE_USE, acording to documentation, you should use:

FILTER_FLAG_HOST_REQUIRED - URL must include host name (like http://www.example.com)

like:

<?php
$url = "https://www.stackoverflow.com";

if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) {
    echo("$url is a valid URL");
} else {
    echo("$url is not a valid URL");
}
?>

And this should work. Hope it helps!

Edit:

The results of the code:

stackoverflow.com is not a valid URL

http://stackoverflow.com is a valid URL

http://www.stackoverflow.com is a valid URL

ww.stackoverflow.com is not a valid URL

http://stackoverflow is a valid URL

As @mickmackusa said, I removed the regex snippet, if you want regex, you could use:

validate url with regular expressions

Or:

URL Validation REGEX - URL just valid with http://

JP. Aulet
  • 4,375
  • 4
  • 26
  • 39
  • Try validating 'https://www.stackoverflow' it still shows as valid url, even domain extension is missing – Alko Jun 11 '17 at 19:20
  • I don't know how you are testing the code, but it works perfectly. 'stackoverflow' IS not a valid url. Did you try this code? Can you post (edit) you current code? – JP. Aulet Jun 11 '17 at 19:27
  • 1
    This is a very comprehensive answer, so I'm not going to compete (you might just want to remove the regex option). Here is the disconnect/monkeywrench: https://regex101.com/r/hGnoeA/2 @JP.Aulet Your pattern looks for zero or more of the 2nd non-capturing group. Alko's actual text was modified when posting the comment (see my demo) The pattern, in this case, is matching the 2nd group using the zero quantifier. Then the 3rd group is matching what should be the 2nd. It would be better if you made a literal `w{3}\.` group that was zero or one. Email address can get messy. Use FILTER. – mickmackusa Jun 11 '17 at 21:35