What are common reasons for the issue of a file being displayed in the browser instead of being downloaded when using PHP for file transfer?

When a file is displayed in the browser instead of being downloaded, it is usually due to the missing or incorrect Content-Disposition header in the PHP code. To force the browser to download the file instead of displaying it, you need to set the Content-Disposition header to "attachment".

<?php
$file = 'example.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);
exit;
?>