How can JavaScript be used in PHP to handle page redirection without causing header errors?

When using JavaScript in PHP to handle page redirection, you need to ensure that the JavaScript code is executed before any headers are sent to avoid header errors. This can be achieved by using output buffering in PHP to capture the JavaScript redirection code and then sending the headers afterwards.

<?php
ob_start();
echo '<script>window.location.replace("https://example.com");</script>';
ob_end_flush();
exit;
?>