How can one prevent the error message "Warning: Cannot modify header information - headers" in PHP when working with headers?

When working with headers in PHP, the error message "Warning: Cannot modify header information - headers" can occur if there is any output sent to the browser before the header() function is called. To prevent this error, make sure that there is no whitespace or any other output before the header() function is used. One common way to solve this is to place the header() function at the beginning of the PHP script before any HTML or whitespace.

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

// Place the header() function at the beginning of the script
header('Location: https://www.example.com');

ob_end_flush(); // Flush the output buffer