How to Validate URL with PHP

Any time a user submits a URL, it is crucial to investigate whether the given URL is valid or not. In this short tutorial, you will find the easiest and most efficient way to validate a URL with the help of PHP. Check out the options below.

The First Option is Using filter_var

The first efficient way of validating a URL is applying the filter_var function with the FILTER_VALIDATE_URL filter. So, the following code should be used for checking whether the ($url) variable is considered a valid URL:

<?php

$url = "http://www.w3docs.com";
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
  echo "$url is a valid URL";
} else {
  echo "$url is not a valid URL";
}

?>

The Second Option is Using preg_match

For checking whether the syntax of a URL address is valid, you are also recommended to use the preg_match regular expression. Also, in the URL, dashes are allowed by regular expressions.

In case there exists an invalid syntax, an error message turns out, as demonstrated in the example below:

<?php
    $website = 'https://www.w3docs';
    $pattern = '/^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w.-]*)*\/?$/';
    if (!preg_match($pattern, $website)) {
     echo "Invalid URL";
    } else {
      echo "URL is valid: " . $website;
    }
  ?>

Describing the filter_var Function

This function is commonly used in PHP for filtering a variable with a given filter. It includes three parameters such as variable, filter, and options.

Describing the preg_match() Regex

The preg_match() regular expression is aimed at searching the string for a pattern. True will be returned when the pattern is there, and, otherwise, false.