What are some common pitfalls when setting headers in PHP for file downloads?

One common pitfall when setting headers in PHP for file downloads is not properly handling file paths or content types. To avoid this issue, make sure to set the correct content type and disposition headers before outputting the file contents.

<?php
$file_path = 'path/to/file.pdf';

if (file_exists($file_path)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
    header('Content-Length: ' . filesize($file_path));

    readfile($file_path);
    exit;
} else {
    echo 'File not found.';
}
?>