What are the best practices for handling if-clauses in PHP to avoid header modification errors?

When using if-clauses in PHP to check conditions before modifying headers, it is important to ensure that no output has been sent to the browser before calling functions like header(). To avoid header modification errors, you can use output buffering to capture any output and prevent it from being sent prematurely. This way, you can safely modify headers based on conditions without encountering errors.

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

// Your code here

if ($condition) {
    header('Location: http://example.com');
    exit;
}

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