What are best practices for securely storing downloadable files on a web server in PHP?

To securely store downloadable files on a web server in PHP, it is important to store the files outside of the web root directory to prevent direct access by users. One common approach is to store the files in a directory outside the web root and use PHP to serve the files by checking user permissions before allowing the download.

<?php
// Define the path to the directory where files are stored
$filePath = '/path/to/secure/directory/';

// Check if the user is authenticated and has permission to download the file
if($userAuthenticated && $userHasPermission) {
    // Get the file name from the request
    $fileName = basename($_GET['file']);

    // Validate the file name to prevent directory traversal attacks
    if (strpos($fileName, '..') === false) {
        // Set the appropriate headers for file download
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');

        // Serve the file
        readfile($filePath . $fileName);
    } else {
        // Invalid file name
        echo 'Invalid file name';
    }
} else {
    // User is not authorized to download the file
    echo 'You are not authorized to download this file';
}
?>