What are the best practices for offering files for download to authorized users in PHP without exposing sensitive information?

When offering files for download to authorized users in PHP, it is important to ensure that sensitive information is not exposed. One way to achieve this is by storing the files outside of the web root directory and using PHP to handle the download process. By checking the user's authorization before allowing the download, you can prevent unauthorized access to the files.

<?php
// Check user authorization here

if($user_authorized) {
    $file_path = '/path/to/file.pdf'; // Path to the file
    $file_name = 'file.pdf'; // Name of the file as it will appear to the user
    
    // Set headers for file download
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . $file_name . '"');
    
    // Output the file
    readfile($file_path);
} else {
    echo 'Unauthorized access';
}
?>