Easy Tutorial
❮ Func Mysqli Get Client Version Func Math Octdec ❯

PHP FILTER_VALIDATE_URL Filter


Example

Determine if the URL format is correct:

<?php
$url = "https://www.tutorialpro.org";

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

Executing the above code outputs:

https://www.tutorialpro.org is a valid URL

Definition and Usage

The FILTER_VALIDATE_URL filter validates the value as a URL.

Possible flags:


Example

The following example removes illegal characters from the variable $url and then checks if it is a valid URL:

<?php
$url = "https://www.tutorialpro.org";

// Remove illegal characters from the URL
$url = filter_var($url, FILTER_SANITIZE_URL);

// Validate the URL
if (filter_var($url, FILTER_VALIDATE_URL)) {
    echo("$url is a valid URL");
} else {
    echo("$url is an invalid URL");
}
?>

The output of the code is as follows:

https://www.tutorialpro.org is a valid URL

The following checks if the URL contains a valid query string:

<?php
// URL without parameters
$url = "https://www.tutorialpro.org";

if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)) {
    echo("$url is a valid URL");
} else {
    echo("$url is an invalid URL");
}

echo PHP_EOL; // Line break

// URL with parameters
$url2 = "https://www.tutorialpro.org?s=php";

if (filter_var($url2, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)) {
    echo("$url2 is a valid URL");
} else {
    echo("$url2 is an invalid URL");
}
?>

The output of the code is as follows:

https://www.tutorialpro.org is an invalid URL
https://www.tutorialpro.org?s=php is a valid URL

❮ Func Mysqli Get Client Version Func Math Octdec ❯