What are some best practices for implementing secure and efficient file downloads in PHP?

To implement secure and efficient file downloads in PHP, it is essential to ensure that the files are served securely, only authorized users have access, and the download process is efficient to handle large files without performance issues. One common practice is to store files outside the web root directory to prevent direct access, validate user permissions before allowing downloads, and use headers to set content type and disposition for secure downloads.

<?php
// Check user permissions before allowing download
if($user->hasPermission('download_files')) {
    $file = '/path/to/file.pdf';
    
    // Set headers for secure download
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="file.pdf"');
    header('Content-Length: ' . filesize($file));
    
    // Output file contents
    readfile($file);
} else {
    echo 'You do not have permission to download this file.';
}
?>