In PHP, what are the best practices for handling and processing external URLs, especially when integrating them into iframes or extracting specific data for display?

When handling external URLs in PHP, it is important to sanitize and validate the input to prevent security vulnerabilities such as cross-site scripting attacks. One way to do this is by using the filter_var function with the FILTER_VALIDATE_URL filter to ensure that the URL is properly formatted. Additionally, you can use the htmlspecialchars function to escape any HTML characters in the URL before displaying it in an iframe or extracting specific data for display.

// Example of sanitizing and validating an external URL
$externalUrl = "https://example.com";
if (filter_var($externalUrl, FILTER_VALIDATE_URL)) {
    $safeUrl = htmlspecialchars($externalUrl);
    // Display the URL in an iframe or extract specific data for display
} else {
    echo "Invalid URL";
}