What are the best practices for avoiding the error of modifying header information in PHP?

Modifying header information in PHP can lead to errors such as "headers already sent" which can cause issues with the display of your webpage. To avoid this error, it is best practice to ensure that no output is sent to the browser before modifying header information. This can be achieved by placing header functions at the beginning of your PHP script before any HTML or whitespace.

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

// Your PHP code here

header('Location: https://www.example.com');
exit();

ob_end_flush(); // Flush the output buffer
?>