How can one prevent the error "Cannot modify header information - headers already sent" in PHP?

The error "Cannot modify header information - headers already sent" in PHP occurs when there is output sent to the browser before header functions are called. To prevent this error, ensure that no output is sent before calling functions like header() or setcookie(). One common solution is to place all header-related functions at the beginning of the script before any output is generated.

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

// Place header-related functions at the beginning of the script
header('Location: https://www.example.com');
exit();

ob_end_flush(); // Flush output buffer
?>