What are the best practices for handling page redirection within an iframe using PHP?

When handling page redirection within an iframe using PHP, it is important to ensure that the redirection works smoothly within the iframe without affecting the parent page. One common approach is to use JavaScript to handle the redirection within the iframe itself.

<?php
// Check if the request is coming from within an iframe
if(isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'example.com') !== false) {
    echo '<script>window.top.location.href = "new_page.php";</script>';
    exit;
} else {
    // Handle redirection for requests not coming from within an iframe
    header('Location: new_page.php');
    exit;
}
?>