What are the potential pitfalls of using PHP to download files and how can they be mitigated?
One potential pitfall of using PHP to download files is that it can expose your server to security vulnerabilities if not handled properly. To mitigate this risk, always sanitize user input to prevent directory traversal attacks, validate file types to prevent unauthorized downloads, and use secure file storage locations.
<?php
$filename = $_GET['filename'];
// Sanitize user input to prevent directory traversal attacks
$filename = basename($filename);
// Validate file type to prevent unauthorized downloads
$allowed_types = array('pdf', 'txt', 'jpg', 'png');
$file_extension = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($file_extension, $allowed_types)) {
die("Invalid file type.");
}
// Use secure file storage locations
$file_path = '/path/to/secure/directory/' . $filename;
// Download the file
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
readfile($file_path);
?>