Completely validate URL with or without http or https
Use filter_var()
as you stated, however, by definition a URL must contain a protocol. Using just http
will check for https
as well:
$url = strpos($url, 'http') !== 0 ? "http://$url" : $url;
Then:
if(filter_var($url, FILTER_VALIDATE_URL)) {
//valid
} else {
//not valid
}
I've also seen this used:
$url = "http://example.com";
if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) {
echo "URL is valid";
}
else {
echo "URL is invalid";
}
Source: http://codekarate.com/blog/validating-url-php