What best practices should be followed to prevent the error message "Cannot modify header information - headers already sent" in PHP?

The error message "Cannot modify header information - headers already sent" in PHP occurs when there is output sent to the browser before PHP attempts to modify headers. To prevent this error, make sure there is no whitespace or output before any header functions are called. One common solution is to place all header modifications at the beginning of the script before any output is sent.

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

// Place header modifications here
header('Location: http://www.example.com');

ob_end_flush(); // Flush output buffer
?>