What are the best practices for setting up a download button in PHP for files located outside the HTML root directory?
When setting up a download button in PHP for files located outside the HTML root directory, it is important to ensure that the file paths are properly handled to prevent unauthorized access to sensitive files. One way to achieve this is by using PHP to read the file contents and serve them to the user through the download button.
<?php
// Define the file path outside the HTML root directory
$file_path = '/path/to/file/outside/html_root/file.pdf';
// Check if the file exists
if (file_exists($file_path)) {
// Set the appropriate headers for a PDF file download
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . basename($file_path));
header('Content-Length: ' . filesize($file_path));
// Read the file and output its contents
readfile($file_path);
exit;
} else {
// Handle file not found error
echo 'File not found.';
}
?>
Related Questions
- Are there any alternative methods or libraries that can be used instead of opendir() in PHP for directory operations?
- What are the potential issues with setting and accessing cookies in PHP scripts, and how can they be resolved?
- What are the potential pitfalls of using ORDER BY in a MySQL query when trying to display top results for each category?