Monday 2 February 2015

FILTER_VALIDATE_URL in PHP

FILTER_VALIDATE_URL

We can validate a url by using FILTER_VALIDATE_URL function in PHP. Here is one simple example
$url='http://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 ";
}
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.

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
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.
http://example.com                      // Wrong, URL Validation failed 
http://example.com/path/filename.htm    // Correct validation passed
http://example.com/                            // Correct validation passed

Validating URL with query string

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
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
http://example.com       // Wrong, URL Validation failed 
http://example.com?id=5        // Correct validation passed
http://example.com/             // Wrong, URL Validation failed 

0 comments:

Post a Comment