What are some best practices to avoid header-related errors in PHP scripts, especially in login systems?

One common issue in PHP scripts, especially in login systems, is header-related errors caused by output being sent before headers are set. To avoid this, always ensure that no output is sent before calling functions like header() to set HTTP headers. One way to achieve this is by placing all PHP code before any HTML content or using output buffering functions like ob_start().

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

// Your PHP code here

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