PHP check if a url is valid using filter_var

URL can simply validate use FILTER_VALIDATE_URL in filter_var().

For example:

$url = "http://www.php.net";

/*** try to validate the URL ***/
if(filter_var($url, FILTER_VALIDATE_URL) === FALSE)
{
	/*** if there is no match ***/
	echo "Sorry, $url is not valid!";
}
else
{
	/*** if we match the pattern ***/
	echo "The URL, $url is valid!<br />";
}

IT can be in a function:

function validate_url($url)
{
    if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) === FALSE)
    {
        /*** if there is no match ***/
        return false;
    }
    else
    {
        /*** if the URL is valid ***/
        return true;
    }
}

By Keenlio, February 12, 2014

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


× 9 = sixty three

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>