What are some common pitfalls to avoid when writing PHP code to prevent header modification errors?

One common pitfall to avoid when writing PHP code to prevent header modification errors is to ensure that no output is sent to the browser before calling functions like header(). This can be achieved by placing all header-related code at the beginning of the script, before any HTML or whitespace. Additionally, using the exit() function after setting headers can prevent any further output that may inadvertently modify headers.

<?php
// Correct way to set headers at the beginning of the script
header("Content-Type: text/html");

// Prevent any further output
exit();
?>