How can the "Cannot modify header information" error be avoided when using header location in PHP?

The "Cannot modify header information" error in PHP occurs when there is output sent to the browser before the header() function is called to set a new location. To avoid this error, make sure there is no output (such as HTML, whitespace, or error messages) before calling header().

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

// Your PHP code here

header("Location: newpage.php"); // Redirect to a new page

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