What are the best practices for combining include() and header() functions in PHP to handle page redirection and templating?

When combining include() and header() functions in PHP to handle page redirection and templating, it is important to ensure that the header() function is called before any output is sent to the browser. This is because header() needs to be sent before any content, including whitespace or HTML tags. To achieve this, you can use output buffering to capture the output of include() and then send the header before outputting the buffered content.

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

// Your templating logic here
include('header.php');

// Your page content here
echo "Welcome to my website!";

include('footer.php');

// Get the buffered content
$content = ob_get_clean();

// Send header before outputting content
header('Location: https://www.example.com');
echo $content;
?>