How can JavaScript be used to create a countdown before redirecting users to another page in PHP?

To create a countdown before redirecting users to another page in PHP, you can use JavaScript to display a countdown timer on the current page. Once the countdown reaches zero, you can then redirect the user to the desired page using PHP's header function.

<!DOCTYPE html>
<html>
<head>
    <title>Countdown Redirect</title>
    <script>
        var countdown = 5; // Countdown time in seconds
        var redirectUrl = 'newpage.php'; // URL to redirect to

        function startCountdown() {
            var countdownInterval = setInterval(function() {
                countdown--;
                document.getElementById('countdown').innerHTML = countdown;

                if (countdown <= 0) {
                    clearInterval(countdownInterval);
                    window.location.href = redirectUrl;
                }
            }, 1000);
        }
    </script>
</head>
<body onload="startCountdown()">
    <h1>Redirecting in <span id="countdown">5</span> seconds...</h1>
</body>
</html>