What are the potential security risks of using PHP to handle file downloads in this manner?
One potential security risk of using PHP to handle file downloads is the possibility of allowing unauthorized access to sensitive files on the server. To mitigate this risk, it is important to validate user input and only allow downloads of files that the user is authorized to access. Additionally, it is crucial to sanitize file paths to prevent directory traversal attacks.
<?php
// Validate user input to ensure they are authorized to download the file
$allowed_files = ['file1.pdf', 'file2.pdf'];
$requested_file = $_GET['file'];
if (!in_array($requested_file, $allowed_files)) {
die("Unauthorized access");
}
// Sanitize file path to prevent directory traversal attacks
$file_path = '/path/to/files/' . basename($requested_file);
// Set appropriate headers for file download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
header('Content-Length: ' . filesize($file_path));
// Output the file content
readfile($file_path);
?>
Related Questions
- What are common errors that beginners encounter when writing PHP scripts, and how can they be resolved?
- What are the potential pitfalls when using fsockopen() and is_resource() to check server connections?
- What are the potential pitfalls of using preg_match to search through an entire database in PHP?