What are some best practices for handling URLs and ensuring their correctness in PHP applications?

When handling URLs in PHP applications, it is important to ensure their correctness to prevent errors and vulnerabilities. One best practice is to sanitize and validate user input to avoid injection attacks and malformed URLs. Additionally, using built-in PHP functions like filter_var() with the FILTER_VALIDATE_URL filter can help validate URLs effectively.

// Example of sanitizing and validating a URL in PHP
$url = filter_var($_POST['url'], FILTER_SANITIZE_URL);

if (filter_var($url, FILTER_VALIDATE_URL)) {
    // URL is valid, proceed with processing
    echo "Valid URL: " . $url;
} else {
    // URL is invalid, handle error accordingly
    echo "Invalid URL";
}