I want to validate a URI (not URL only) in PHP, though couldn't find any way to do this.
PHP does have parse_url() but it is not for URIs, it would be helpful to find a proper way to validate URI structures such as the following:
content://com.example.provider/articles/?optional=queries
To validate URIs, you can use the FILTER_VALIDATE_URL filter with the filter_var() function in PHP.
$uri = "content://com.example.provider/articles/?optional=queries"
if (filter_var($uri, FILTER_VALIDATE_URL)) {
// Valid URI, do something here.
}
You can try the code below:
$url = "http://www.google.com";
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
Needs to filter as well to remove illegal characters.
$url = "http://www.google.com";
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
// Validate url
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
Here, the URL is required to have a query string to be valid:
$url = "https://www.w3schools.com";
if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}