Are there any best practices for managing file downloads in PHP to ensure proper user interaction?
When managing file downloads in PHP, it is important to ensure proper user interaction by setting appropriate headers, handling errors gracefully, and validating user input to prevent security risks. One common best practice is to use the `header()` function to send the correct content type and disposition headers before outputting the file contents.
<?php
// Validate user input to prevent directory traversal attacks
$file = 'path/to/file.pdf';
if (file_exists($file)) {
// Set appropriate headers for file download
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
// Output the file contents
readfile($file);
exit;
} else {
// Handle error if file does not exist
echo 'File not found';
}