What are some best practices for securely managing file downloads in PHP scripts?
When managing file downloads in PHP scripts, it is important to ensure that the files are served securely to prevent unauthorized access or execution of malicious code. One best practice is to store the files outside of the web root directory to prevent direct access. Additionally, use proper authentication and authorization mechanisms to restrict access to authorized users only.
<?php
// Check if user is authenticated and authorized to download the file
if($authenticated && $authorized) {
$file = '/path/to/file.pdf';
// Check if the file exists
if(file_exists($file)) {
// Set appropriate headers for file download
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
// Read the file and output it to the browser
readfile($file);
exit;
} else {
echo 'File not found.';
}
} else {
echo 'Unauthorized access.';
}
?>