What are the best practices for allowing PHP scripts to download files while maintaining security?
When allowing PHP scripts to download files, it is important to ensure security measures are in place to prevent unauthorized access or malicious files from being downloaded. One way to do this is by using a combination of PHP headers to set content type and disposition, validating the file path to prevent directory traversal attacks, and restricting access to authenticated users only.
<?php
// Check if user is authenticated
if($authenticated_user) {
$file_path = '/path/to/file.pdf';
// Validate file path to prevent directory traversal
if (strpos($file_path, '/path/to/') === 0) {
// Set appropriate headers for file download
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
readfile($file_path);
exit;
} else {
// Invalid file path
echo 'Invalid file path';
}
} else {
// User not authenticated
echo 'Access denied';
}
?>