How can PHP be used to prevent direct file downloads via URL?

Direct file downloads via URL can be prevented by placing the files outside of the web root directory and using PHP to serve the files instead. By using PHP to read and output the file contents, you can add authentication and authorization checks to ensure that only authorized users can access the files.

<?php
// Check if the user is authenticated before serving the file
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true) {
    $file = '/path/to/file.pdf'; // Path to the file
    $file_name = basename($file);
    
    // Check if the file exists
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf'); // Set the appropriate content type
        header('Content-Disposition: attachment; filename="' . $file_name . '"');
        readfile($file);
        exit;
    } else {
        echo 'File not found.';
    }
} else {
    echo 'You are not authorized to access this file.';
}
?>