What are some best practices for handling redirects and delays in PHP scripts with JavaScript?

When handling redirects and delays in PHP scripts with JavaScript, it is important to ensure that the redirect or delay is properly implemented to avoid any issues such as infinite loops or unexpected behavior. One common approach is to use the header() function in PHP to send a redirect header, and then use JavaScript to handle any delays or additional logic on the client side.

<?php
// Redirect to a new page after 5 seconds
header("Refresh:5; url=newpage.php");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Redirecting...</title>
    <script>
        // Optional JavaScript for additional logic or delays
        setTimeout(function() {
            window.location.href = 'newpage.php';
        }, 5000); // 5 seconds
    </script>
</head>
<body>
    <p>Redirecting to new page in 5 seconds...</p>
</body>
</html>