What are the best practices for securely downloading files from a server in PHP?
When downloading files from a server in PHP, it is important to ensure that the process is secure to prevent unauthorized access or malicious attacks. One best practice is to use proper validation to check if the user has permission to download the file. Additionally, it is recommended to use file paths that are not directly accessible by the public and to sanitize user input to prevent directory traversal attacks.
<?php
// Check if user has permission to download the file
if (/* insert your permission check logic here */) {
$file = '/path/to/your/file.pdf';
// Sanitize the file path to prevent directory traversal attacks
$file = realpath($file);
// Set appropriate headers for the file download
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Length: ' . filesize($file));
// Read the file and output it to the browser
readfile($file);
} else {
// Handle unauthorized access
echo 'You are not authorized to download this file.';
}
?>