What are potential pitfalls to consider when using the header function in PHP to redirect to another page?

One potential pitfall when using the header function in PHP to redirect to another page is that the header must be sent before any output is displayed to the browser. This means that if there is any HTML content or whitespace before the header function is called, it will result in an error. To solve this issue, you can use output buffering to capture all output before sending any headers.

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

// Your PHP code here

ob_end_clean(); // Clean (erase) the output buffer
header("Location: newpage.php"); // Redirect to new page
exit; // Stop script execution
?>