How can PHP be used to download files from a protected directory?

When downloading files from a protected directory in PHP, you need to ensure that the user has the necessary permissions to access the files. One way to achieve this is by using PHP to authenticate the user before allowing the download to proceed. This can be done by checking the user's credentials against a database or some other form of authentication mechanism.

<?php
// Check user authentication here

if($authenticated) {
    $file = 'path/to/protected/file.pdf';

    if(file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename=' . basename($file));
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    } else {
        echo 'File not found.';
    }
} else {
    echo 'Access denied.';
}
?>