How can the "header already sent" error be prevented when using the header() function for page redirection in PHP?

When using the header() function for page redirection in PHP, the "header already sent" error can be prevented 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 HTML, whitespace, or error messages) sent before the header() function is called, which prevents the header from being set properly. To prevent this error, make sure to call the header() function before any output is sent to the browser.

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

// Redirect to a new page after 3 seconds
header("refresh:3;url=destination.php");

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