What best practices should be followed when using PHP to handle file downloads on a website?
When handling file downloads in PHP, it is important to ensure that the files are served securely and efficiently. One best practice is to use proper headers to set the content type and disposition of the file being downloaded. Additionally, it's recommended to validate the file path and permissions to prevent unauthorized access to sensitive files.
<?php
$file = 'path/to/file.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo 'File not found';
}
?>