$url='https://www.example'; //Change this value to check different URL
if(filter_var($url,FILTER_VALIDATE_URL)){
echo " Correct , URL Validation passed ";
}else{
echo " Wrong , URL Validation failed ";
}
We can validate a URL (Uniform Resource Locator) by using FILTER_VALIDATE_URL function in PHP.
In the above code we can get the message that Correct, URL Validation passed. Same way you can change the data and get the staus.
Optional Flags
FILTER_FLAG_SCHEME_REQUIRED - additional check of RFC compliant (like http://example)
FILTER_FLAG_HOST_REQUIRED - additional check of host name (like http://www.example.com
FILTER_FLAG_PATH_REQUIRED - additional check of path to domain name (like www.example.com/php_tutorial/)
FILTER_FLAG_QUERY_REQUIRED - With a query string (like "example.php?id=34&cat=student&class=Four")
FILTER_FLAG_SCHEME_REQUIRED & FILTER_FLAG_HOST_REQUIRED are deprecated in PHP 7.3 as they are included within FILTER_VALIDATE_URL.
Validating URL with path
We can add one optional flag FILTER_FLAG_PATH_REQUIRED to check if any path is added after the URL. Without presence of a path this validation will fail. This flag checks minimum one forward slash ( / ) after the URL to be present. Here is the code
With the optional flag of FILTER_FLAG_QUERY_REQUIRED we can validate URL only if a valid query string is present ( along with URL ) . Here is the code to check