What are the potential security risks of allowing direct file downloads via URL in PHP?
Allowing direct file downloads via URL in PHP can pose several security risks, such as exposing sensitive files, allowing malicious files to be downloaded, and potential denial of service attacks. To mitigate these risks, it is recommended to implement proper validation and sanitization of the file path before allowing the download to prevent unauthorized access and ensure that only allowed file types can be downloaded.
// Example of validating and sanitizing the file path before allowing download
$allowed_files = array("file1.pdf", "file2.jpg", "file3.txt");
$file = $_GET['file'];
if (in_array($file, $allowed_files)) {
$file_path = 'path/to/files/' . $file;
// Perform additional checks if needed
if (file_exists($file_path)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
readfile($file_path);
exit;
} else {
echo 'File not found.';
}
} else {
echo 'Invalid file.';
}