What best practices should be followed when using iframes to include external files in PHP?

When using iframes to include external files in PHP, it is important to ensure that the external file is secure and trusted to prevent any security vulnerabilities. It is recommended to sanitize user input and validate the URL before including it in the iframe to prevent any potential XSS attacks. Additionally, setting the sandbox attribute on the iframe can help mitigate any potential risks associated with including external content.

<?php
$url = "https://www.example.com/externalfile.php";
$validated_url = filter_var($url, FILTER_VALIDATE_URL);

if ($validated_url) {
    echo '<iframe src="' . $validated_url . '" sandbox="allow-same-origin allow-scripts"></iframe>';
} else {
    echo 'Invalid URL';
}
?>