Horje
PHP Forms Validate URL

Form validation is a necessary process that must be done before submitting the data to the database. Any time a user submits a URL, it becomes crucial to investigate whether the given URL is valid or not. We can use PHP to validate the URLs that are submitted through an HTML form.

Using filter_var( ) Function

To validate a URL, the first approach is to use the filter_var( ) method with the FILTER_VALIDATE_URL filter. This method is widely used in PHP to filter a variable with a specific filter. It ensures that URLs are correctly formatted and secure, thus reducing the chances of security vulnerabilities.

Example: Implementation to validate URL in PHP Forms using filter_var( ).

PHP

<?php
   
// Taking a sample URL
 
// Checking if the URL is valid or not
if (filter_var($url, FILTER_VALIDATE_URL)) {
    echo "$url is a VALID URL";
} else {
    echo "$url is a INVALID URL";
}
?>

Output

https://www.example.in is a VALID URL






Using preg_match( ) Function

The preg_match( ) method is commonly used to search the given string using a pattern. This pattern is created using regular expression.

Example: Implementation to validate URL in PHP Forms using preg_match( )

PHP

<?php
// Taking a sample URL
 
 
// Checking if the URL is valid or not
if (
    preg_match(
"/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",
        $url
    )
) {
    echo "$url is a VALID URL";
} else {
    echo "$url is a INVALID URL";
}
?>

Output

https://www.example.in is a VALID URL







Reffered: https://www.geeksforgeeks.org


PHP

Related
PHP Program to Check if a Given Letter is Vowel or Consonant PHP Program to Check if a Given Letter is Vowel or Consonant
PHP Program to Calculate pow(x, n) PHP Program to Calculate pow(x, n)
Convert Number to Binary Coded Decimal in PHP Convert Number to Binary Coded Decimal in PHP
PHP Program to Calculate Root Mean Square PHP Program to Calculate Root Mean Square
PHP Program to Count Zeros and Ones in Binary Representation of a Number PHP Program to Count Zeros and Ones in Binary Representation of a Number

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13