Url Validation

I have searched around this topic and don’t get a exact solution I need, so posting a new thread.

I need a url validation method in php, but it should allow following types

google.com
ww.google.com/
sub.google.co.in
http://google.com
https://www.google.com
ftp://google.com/sub/index.php?id=124&id2=222#field,2013
and all possible urls

Please help me…

filter_var('http://example.com', FILTER_VALIDATE_URL)

This returns google.com as invalid :frowning:

filter_var('example.com', FILTER_VALIDATE_URL)

failed :frowning:

example.com” is not a valid URL.
http://example.com” is a valid URL.

You see what is missing in the first one?

Ok I understand but a user may or maynot enter the http:// with the url in the url text feild, but I have to validate both.

What you could do is the following:


$url = 'http://'.str_replace('http://','',$url);
$valid = filter_var($url,FILTER_VALIDATE_URL);

You can try adding a protocol if it isn’t there:


if (preg_match('@^[a-z]+\\\\:\\\\/\\\\/@', $url)==false) {
$url = "http://" . $url;
}

some excellent advice and interesting logics, really good to read.