FILTER_VALIDATE_URL checks URL syntax. Add flags only for requirements that are actually part of your application rules.
$url = 'https://www.example.com/docs';
var_dump(filter_var($url, FILTER_VALIDATE_URL));
$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. 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
if(filter_var($_GET['url'],FILTER_VALIDATE_URL,FILTER_FLAG_PATH_REQUIRED)){
echo " Correct , URL Validation passed ";
}else{
echo " Wrong , URL Validation failed ";
}
Here is the list of URL which will pass and which will fail in the validation.
https://example.com // Wrong, URL Validation failed
https://example.com/path/filename.htm // Correct validation passed
https://example.com/ // Correct validation passed
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
if(filter_var($_GET['url'],FILTER_VALIDATE_URL,FILTER_FLAG_QUERY_REQUIRED)){
echo " Correct , URL Validation passed ";
}else{
echo " Wrong , URL Validation failed ";
}
Here is a list of URL which will pass and which will fail the URL validation process
https://example.com // Wrong, URL Validation failed
https://example.com?id=5 // Correct validation passed
https://example.com/ // Wrong, URL Validation failed
Filter reference
Validating IP address
Sanitize URL
Validating Email address
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.