How can headers in PHP be effectively used for redirects without causing header modification errors?

When using headers in PHP for redirects, it's important to ensure that no output has been sent to the browser before the header functions are called. To prevent header modification errors, you can use output buffering to capture any output before sending headers.

<?php
ob_start(); // Start output buffering

// Your PHP code here

ob_end_clean(); // Clean (delete) the output buffer
header("Location: https://www.example.com"); // Redirect to the desired URL
exit(); // Stop script execution after redirect
?>