How can the PHP syntax error "headers already sent" be avoided when using header functions for page redirection?

When using header functions for page redirection in PHP, the "headers already sent" error can be avoided by ensuring that no output is sent to the browser before calling the header function. This error occurs when there is any output (such as whitespace or HTML tags) before the header function is called, which prevents the headers from being modified. To avoid this error, make sure to place the header function calls at the beginning of the PHP script before any output is generated.

<?php
// Ensure no output is sent before calling header function
ob_start();

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