What are some best practices for managing file downloads in PHP to ensure user privacy and security?

When managing file downloads in PHP, it is essential to ensure user privacy and security by implementing proper measures such as checking user permissions, sanitizing file names, and using secure download methods like sending files through PHP instead of direct links.

<?php
// Check user permissions before allowing download
if($userHasPermission) {
    $file = 'path/to/file.pdf';
    
    // Sanitize file name to prevent directory traversal
    $fileName = basename($file);
    
    // Send file through PHP to prevent direct access
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    readfile($file);
} else {
    echo 'You do not have permission to download this file.';
}
?>