How can PHP developers ensure that file download functionality is secure and efficient on their websites?
To ensure file download functionality is secure and efficient on websites, PHP developers can use the following code snippet to verify the file path, set appropriate headers to prevent direct access, and stream the file to the user.
<?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('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
echo 'File not found.';
}
?>