How can PHP developers ensure that sensitive files are not accessible through direct URLs while still allowing for secure downloads?

PHP developers can ensure that sensitive files are not accessible through direct URLs by storing them outside the web root directory and using PHP script to handle the file downloads. By using PHP headers to send the file to the user, developers can control access to the file and ensure that it is only accessible through the script.

<?php
// Set the file path
$file = '/path/to/sensitive/file.pdf';

// Check if the user is authenticated
if($user_authenticated) {
    // Set the appropriate headers
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Content-Length: ' . filesize($file));

    // Send the file to the user
    readfile($file);
} else {
    // Redirect the user or display an error message
    echo 'You are not authorized to access this file.';
}
?>