How to Validate URL with PHP

  1. Using filter_var
  2. Using preg_match

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.

A. 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:

$url = "";
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
    echo("$url is a valid URL");
} else {
    echo("$url is not a valid URL");

B. 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:

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  $websiteErr = "Invalid URL";

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.

Do you find this helpful?

Related articles