Are there any best practices for securely handling file downloads in PHP?

When handling file downloads in PHP, it is important to ensure that the files are served securely to prevent unauthorized access or execution of malicious code. One best practice is to store the files outside of the web root directory to prevent direct access. Additionally, it is recommended to use proper authentication and authorization mechanisms to control access to the files.

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

    if(file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename=' . basename($file));
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    } else {
        echo 'File not found.';
    }
} else {
    echo 'Unauthorized access.';
}
?>