What best practices should be followed when creating PHP scripts to handle file listings and downloads?
When creating PHP scripts to handle file listings and downloads, it is important to ensure proper security measures are in place to prevent unauthorized access to sensitive files. This can be achieved by validating user input, sanitizing file paths, and implementing access control checks. Additionally, it is recommended to use PHP functions like `scandir()` for listing files and `readfile()` for downloading files securely.
<?php
// Validate user input for file path
$file_path = $_GET['file'];
if (!is_string($file_path) || strpos($file_path, '..') !== false) {
die('Invalid file path');
}
// Sanitize file path
$file_path = realpath('uploads/' . $file_path);
// Check if file exists and is readable
if (file_exists($file_path) && is_readable($file_path)) {
// Set appropriate headers for file download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
// Output file contents
readfile($file_path);
} else {
die('File not found or inaccessible');
}
?>