What are some best practices for securely handling file downloads in PHP, especially when the files are stored outside the document root?

When handling file downloads in PHP, especially when the files are stored outside the document root, it is important to ensure that the files are securely accessed to prevent unauthorized users from downloading sensitive information. One best practice is to use PHP to handle the file downloads, rather than directly linking to the file. This allows you to perform authentication and authorization checks before serving the file to the user.

<?php
// Check if user is authenticated and authorized to download the file
if($authenticated && $authorized) {
    $file = '/path/to/file/secret.pdf'; // Path to the file outside the document root

    // Set appropriate headers for file download
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

    // Read the file and output it to the browser
    readfile($file);
    exit;
} else {
    // Handle unauthorized access
    echo "Unauthorized access!";
}
?>