What are the potential pitfalls of modifying headers in PHP scripts and how can they be avoided?

Modifying headers in PHP scripts can lead to errors such as "headers already sent" if not done correctly. To avoid this issue, it is important to ensure that no output is sent to the browser before modifying headers. This can be achieved by placing header modification functions at the beginning of the script before any output is sent.

<?php
// Avoid modifying headers after output has been sent
ob_start(); // Start output buffering

// Modify headers
header("Content-Type: text/html");

// Output content
echo "Hello, World!";

ob_end_flush(); // Flush output buffer
?>