free stats

How to validate a URL in PHP

Last Update : 12 Dec, 2022 How to Guide in PHP

In this article, you will learn to check if the user input URL is valid.

When submitting some web forms, users have to input their URLs for that form. it is very important to check submitted URL is valid or not before processing the submitted data or storing data in the database. 

The following PHP code example shows validate a URL in PHP. Here, we use the PHP in-built function of filter_var() with FILTER_VALIDATE_URL Filter. You can easily validate your URL using this function and filter in PHP.

See the following code for checking if the $mysite variable is a valid URL.

<?php

	$mysite = "http://www.uxpython.com";

	if (filter_var($mysite, FILTER_VALIDATE_URL) == true) {
	    echo($mysite." is a valid URL");
	} else {
	    echo($mysite." is not a valid URL");
	}

?>

This program produces the following result -:

http://www.uxpython.com is a valid URL

 

You found this tutorial / article valuable? Need to show your appreciation? Here are some options:

01. Spread the word! Use following buttons to share this tutorial / article link on your favorite social media sites.

02. Follow us on Twitter, GitHub ,and Facebook.