What are the potential pitfalls of using header() function to force a download window in PHP?

One potential pitfall of using the header() function to force a download window in PHP is that it may not work as expected if there is any output sent to the browser before the headers are set. To solve this issue, you can use output buffering to capture any output before sending headers.

<?php
ob_start();

// Your file processing code here

// Set headers for download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.txt"');

ob_end_flush();
exit;
?>