How can PHP scripts be used to manage and control file downloads to ensure security and prevent unauthorized access?

To manage and control file downloads using PHP, you can implement a script that checks for proper authentication before allowing access to the file. This can be done by verifying user credentials, checking permissions, and ensuring that the file being requested is allowed to be downloaded. By implementing these security measures, you can prevent unauthorized access to sensitive files.

<?php
// Check user authentication before allowing download
if(isset($_SESSION['user_id'])) {
    $file_path = '/path/to/file.pdf'; // Specify the file path
    $file_name = basename($file_path);

    // Check if the file exists and is readable
    if(file_exists($file_path) && is_readable($file_path)) {
        // Set appropriate headers for file download
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $file_name . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file_path));

        // Read the file and output its contents
        readfile($file_path);
        exit;
    } else {
        echo 'File not found or inaccessible.';
    }
} else {
    echo 'Unauthorized access.';
}
?>