How to validate a URL in PHP
It is very important to check URL is valid. In this article, We have shared with you how to validate URL in PHP. Using filter_var() function with FILTER_VALIDATE_URL Filters, we can easily validate a URL in PHP.
Using: regular function preg_match() validates an URL:
1 2 3 4 5 6 7 8 |
// Web URL $website = "https://techarise.com"; // Validate URL if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { echo ("$website is a valid URL"); } else { echo ("$website is not a valid URL"); } |
Using: FILTER_VALIDATE_URL filter validates an URL:
1 2 3 4 5 6 7 8 |
// Web URL $website = "https://techarise.com"; // Validate URL if (filter_var($website, FILTER_VALIDATE_URL) === FALSE) { echo ("$website is a valid URL"); } else { echo ("$website is not a valid URL"); } |