PHP FILTER_VALIDATE_URLFilters


PHP Filter 参考手册Complete PHP Filter Reference Manual

Example

Check if the URL format is correct:

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

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

The output of the above code is:

https://www.example.com 是正确的 URL

Definition and Usage

The FILTER_VALIDATE_URL filter validates the value as a URL.

  • Name: "validate_url"
  • ID-number: 273

Possible flags:

  • FILTER_FLAG_SCHEME_REQUIRED - Requires the URL to be an RFC-compatible URL (e.g., http://example)
  • FILTER_FLAG_HOST_REQUIRED - Requires the URL to contain a host name (e.g., http://www.example.com)
  • FILTER_FLAG_PATH_REQUIRED - Requires the URL to contain a path after the domain name (e.g., www.example.com/example1/test2/)
  • FILTER_FLAG_QUERY_REQUIRED - Requires the URL to contain a query string (e.g., "example.php?name=Peter&age=37")

Example

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

Example

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

// 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.example.com 是正确的 URL

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

Example

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

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; // Newline character

// URL with parameters
$url2 = "https://www.example.com?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.example.com 是错误的 URL
https://www.example.com?s=php 是正确的 URL


PHP Filter 参考手册Complete PHP Filter Reference Manual Other Extensions