How can PHP scripts be used to generate headers for file downloads with correct content types and filenames?

When serving files for download using PHP, it's important to set the correct headers to ensure the browser interprets the file correctly. This includes setting the Content-Type header to the appropriate MIME type and specifying the filename using the Content-Disposition header. By setting these headers correctly, you can ensure that files are downloaded with the correct content type and filename.

<?php
$file = 'example.pdf';
$filename = 'downloaded_file.pdf';

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($file);
exit;
?>