Validate URL in PHP
You can validate URL in PHP using regular expression or using validate filters
Validate URL in PHP using regular expression:
Example:-
<?php
// Write you regular expression pattern to match URL
$pattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
// Assign URL to $URL variable
$URL = 'http://example.com?id=112&name=roop';
// Check url using preg_match
if ( preg_match($pattern, $URL) ) {
echo "Valid URL";
} else {
echo "Invalid URL";
}
?>
Validate URL using validate filters:
Example:-
<?php
$URL = "https://techieroop.com";
if (filter_var($URL, FILTER_VALIDATE_URL)) {
echo "URL is Valid";
}
else {
echo "URL is Invalid";
}
?>
Validate URL using validate filters with flag value:
Flags:-
FILTER_FLAG_PATH_REQUIRED : Requires URL to have a path in URL the domain name (like www.example.com/Orders/order/)
FILTER_FLAG_QUERY_REQUIRED : Requires URL to have a query string (like “order.php?product=smartphone&camera=5m”)
Example:-
<?php
$URL = "www.example.com/Orders/order/";
if( filter_var($URL, FILTER_VALIDATE_URL,FILTER_FLAG_PATH_REQUIRED)) {
echo "URL is not valid";
} else {
echo "URL is valid";
}
?>
(Visited 1,678 times, 7 visits today)