What are common issues with forcing file downloads in PHP scripts?

Common issues with forcing file downloads in PHP scripts include incorrect headers being set, leading to the file being displayed in the browser instead of downloaded, or the downloaded file being corrupted. To solve this, make sure to set the correct headers, such as Content-Type and Content-Disposition, to force the browser to download the file.

<?php
// Set the file path
$file = 'example.pdf';

// Set the headers to force download
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));

// Output the file
readfile($file);
exit;
?>