How can PHP headers be utilized to control the download of files in a secure manner?
When serving files for download in PHP, it's important to use headers to control the download process securely. This can include setting the appropriate content type, content disposition, and ensuring that the file is only accessible to authorized users.
<?php
// Set the content type and disposition for secure file download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.pdf"');
// Check if user is authorized to download the file
if($userIsAuthorized) {
// Serve the file for download
readfile('path/to/example.pdf');
} else {
// Return an error message or redirect unauthorized users
echo 'You are not authorized to download this file.';
}
?>