What are the potential pitfalls of directly downloading files using PHP headers?
Potential pitfalls of directly downloading files using PHP headers include lack of proper validation and security measures, potential for file path exposure, and susceptibility to malicious attacks such as file injection. To mitigate these risks, it is important to sanitize user input, validate file types, and store files outside of the web root directory.
<?php
// Validate and sanitize user input
$file = 'path/to/files/' . basename($_GET['file']);
// Check if the file exists and is allowed for download
if (file_exists($file) && in_array(pathinfo($file, PATHINFO_EXTENSION), ['pdf', 'jpg', 'png'])) {
// Set appropriate headers for file download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
// Read the file and output its content
readfile($file);
exit;
} else {
// Handle invalid file or unauthorized access
echo 'Invalid file or unauthorized access.';
}
?>