What are the best practices for handling output before using header functions in PHP?

When using header functions in PHP to send HTTP headers, it is important to ensure that no output has been sent to the browser before calling these functions. To prevent issues with headers already being sent, it is recommended to use output buffering to capture any output before sending headers.

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

// Your PHP code here

ob_end_clean(); // Clean (discard) the output buffer
header('Location: http://example.com'); // Example of using header function
exit; // Ensure script stops executing after sending headers
?>