What potential pitfalls should be considered when implementing file downloads in PHP, especially when dealing with attachments in emails?
When implementing file downloads in PHP, especially when dealing with attachments in emails, potential pitfalls to consider include ensuring proper file validation to prevent unauthorized access, handling large file sizes to avoid memory exhaustion, and setting appropriate headers to force file downloads instead of displaying them in the browser.
// Example code snippet for handling file downloads in PHP
// Validate file path to prevent unauthorized access
$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));
// Read and output file contents
readfile($file);
exit;
} else {
// Handle file not found error
echo 'File not found.';
}