What are common pitfalls when using header() function in PHP, especially in the context of header redirection?

One common pitfall when using the header() function in PHP for redirection is that headers must be sent before any output to the browser. To solve this issue, make sure that there is no whitespace or output before the header() function is called. Additionally, always use exit() or die() after the header() function to prevent any further code execution.

<?php
ob_start(); // Start output buffering
header("Location: https://www.example.com");
ob_end_flush(); // Flush output buffer
exit(); // Terminate script execution
?>