How can you securely handle external URLs in PHP?

When handling external URLs in PHP, it is important to sanitize and validate the input to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. One way to securely handle external URLs is to use the filter_var() function with the FILTER_VALIDATE_URL filter to validate the URL format. Additionally, you can use the htmlspecialchars() function to escape any HTML characters in the URL to prevent XSS attacks.

// Example of securely handling external URLs in PHP
$externalUrl = "https://www.example.com";

// Validate the URL format
if (filter_var($externalUrl, FILTER_VALIDATE_URL)) {
    // Escape HTML characters in the URL
    $safeUrl = htmlspecialchars($externalUrl);
    
    // Use the safe URL in your application
    echo "Safe URL: " . $safeUrl;
} else {
    echo "Invalid URL";
}