How can PHP be used to prevent users from accessing the direct path of a download file, especially for PDFs?

Users can be prevented from accessing the direct path of a download file, such as a PDF, by storing the files outside of the web root directory and using PHP to handle the file downloads. By using PHP to serve the files, you can authenticate users before allowing them to download the file, ensuring that only authorized users can access the content.

<?php
// Check if user is authenticated
if($user_authenticated) {
    $file_path = '/path/to/your/file.pdf';
    
    // Set headers for PDF file download
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="file.pdf"');
    
    // Output the file content
    readfile($file_path);
} else {
    // Redirect or display an error message
    echo 'You are not authorized to access this file.';
}
?>