What best practices should be followed to avoid the "Cannot modify header information" error in PHP?

The "Cannot modify header information" error in PHP occurs when there is an attempt to modify HTTP headers after they have already been sent to the client. To avoid this error, it is important to ensure that no output is sent to the browser before calling functions like header(). One common practice is to place all header-related code at the beginning of the script before any HTML or whitespace.

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

// Place header-related code at the beginning
header('Location: https://www.example.com');
exit();

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