How can one ensure that the file download functionality in PHP is secure and efficient?
To ensure that the file download functionality in PHP is secure and efficient, it is important to validate user input, check file permissions, sanitize file names, and use appropriate headers to prevent direct access to files on the server. Additionally, consider implementing rate limiting to prevent abuse of the download functionality.
<?php
// Validate user input (e.g., check if the file exists)
$file = 'example.pdf';
if (file_exists($file)) {
// Check file permissions
if (is_readable($file)) {
// Sanitize file name
$filename = basename($file);
// Set appropriate headers
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
// Output the file content
readfile($file);
exit;
} else {
echo 'File is not readable.';
}
} else {
echo 'File not found.';
}
?>