You are currently viewing PHP: How to Validate URLs using filter_var() Function

PHP: How to Validate URLs using filter_var() Function

Validating URLs is a crucial task in web development, ensuring that the URLs provided by users or retrieved from external sources are properly formatted and valid. In PHP, you can use the filter_var() function along with the FILTER_VALIDATE_URL flag to easily validate URLs. In this blog post, we will explore how to validate URLs using the filter_var() function in PHP.

This PHP code checks whether a given URL is well-formed or not, using the built-in filter_var() function with the FILTER_VALIDATE_URL filter. If the URL is well-formed, it will output “URL provided is well formed.”. It will output “The provided URL is not valid.” otherwise.

<?php

$url = "https://www.coderscratchpad.com";

if(filter_var($url, FILTER_VALIDATE_URL)) {

    echo "The provided URL is well-formed.";

} else {

    echo "The provided URL is not well-formed. Please provide a valid URL.";

}

This code can be useful in web applications where user input includes URLs, as it can quickly validate whether the URL is properly formatted or not. However, it is important to note that this validation only checks if the URL is properly formed and not if the URL actually exists or is accessible.

I hope that’s been informative to you. If you wish to learn more about PHP, please subscribe to our newsletter today and continue your PHP learning journey with us!

Leave a Reply