What are some best practices for handling URL validation and formatting in PHP?

When handling URL validation and formatting in PHP, it is important to ensure that the URLs are properly formatted and valid to prevent security vulnerabilities or errors in your application. One way to achieve this is by using PHP's built-in filter_var function with the FILTER_VALIDATE_URL filter option. This function will validate the URL format according to the specified filter.

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

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