What are best practices for structuring PHP code to avoid header modification errors?

When structuring PHP code to avoid header modification errors, it is essential to ensure that no output is sent to the browser before calling the header() function. To achieve this, it is recommended to place all header-related functions at the beginning of the script, before any HTML or whitespace. Additionally, using output buffering functions like ob_start() and ob_end_flush() can help prevent header modification errors.

<?php
ob_start();

// Place header-related functions at the beginning
header('Content-Type: text/html');

// Other PHP code here

ob_end_flush();
?>