What are the best practices for using header() function in PHP to avoid "headers already sent" error?

When using the header() function in PHP, it is important to ensure that no output has been sent to the browser before calling this function. This is because headers must be sent before any actual output is sent to the browser. To avoid the "headers already sent" error, make sure to call the header() function before any output is generated, such as HTML, whitespace, or even error messages.

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

// Your PHP code here

header("Location: https://www.example.com");
exit();

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