How To Validate URL In PHP With Regex

Websolutionstuff | Apr-13-2021 | Categories : Laravel PHP

Hello Guys,

In this tutorial we will see how to validate URL in PHP with regex. also you can implement in laravel or php. here we will give you example of validate url with regular expression and without regular expression so you can both way to implement validate url in php or laravel.

When a URL is submitted from a form input by the user, it is very important to check this URL is valid or not before taking any action on it. So here we will provide the simple PHP code to validate URL in PHP. 

PHP provide filter_var() inbuilt function with FILTER_VALIDATE_URL filter. So, we can easily validates a URL in PHP using javascript regex or regular expression .

 

Example : PHP FILTER_VALIDATE_URL Filter

 

<!DOCTYPE html>
<html>
<body>

<?php
// Variable to check
$url = "https://www.websolutionstuff.com";

// Validate url
if (filter_var($url, FILTER_VALIDATE_URL)) {
  echo("Enter URL is a valid URL");
} else {
  echo("Enter URL is not a valid URL");
}
?>

</body>
</html>

 

 

Possible  flags of validate URL in PHP 

FILTER_FLAG_HOST_REQUIRED - URL must include host name (like https://www.websolutionstuff.com)
FILTER_FLAG_PATH_REQUIRED - URL must have a path after the domain name (like www.websolutionstuff.com/post)

 

Example : Validate URL With Regex

Above function is simply check URL vaidation. If you want to check or validate URL manually or more securely then you can use regular expression. So here I will give example of code.

 

<?php 

$regex = "((https?|ftp)\:\/\/)?";
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?";
$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})";
$regex .= "(\:[0-9]{2,5})?";
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?";
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?";

$url = 'https://websolutionstuff.com/';

if (preg_match("/^$regex$/i", $url)) {
   echo('Enter URL is a valid URL');
}

 

Recommended Post
Featured Post
How to Install PHP Soap Extension in Ubuntu 23.04
How to Install PHP Soap Extens...

Hey fellow developers! Today, let's tackle the installation of the PHP SOAP extension on our Ubuntu 23.04 systems. I...

Read More

Jan-31-2024

Laravel 9 Inner Join Query Example
Laravel 9 Inner Join Query Exa...

In this article, we will see laravel 9 inner join query example. Also, see how to join two tables in laravel 9. In larav...

Read More

Mar-30-2022

Laravel 8 Custom Email Verification Tutorial
Laravel 8 Custom Email Verific...

In this article, we will see an example of laravel 8 custom email verification. Many web applications require users...

Read More

Dec-29-2021

How to Upload File on the FTP Server Using PHP
How to Upload File on the FTP...

In this small post i will show you how to upload file on the ftp server using php. As we know there are many ftp functio...

Read More

May-20-2021