What are the best practices for handling user authentication and file downloads in PHP to prevent unauthorized access to download URLs?

To prevent unauthorized access to download URLs in PHP, it is important to implement user authentication before allowing file downloads. One common approach is to generate a unique download token for each user and validate it against the user's session or database record before serving the file. Additionally, it is recommended to store the files outside of the web root directory to prevent direct access.

// Check if user is authenticated before allowing file download
session_start();
if (!isset($_SESSION['user_id'])) {
    header('HTTP/1.1 401 Unauthorized');
    exit();
}

// Validate download token against user's session or database record
$token = $_GET['token'];
$user_id = $_SESSION['user_id'];

// Check if token is valid for the user
if (!isValidDownloadToken($user_id, $token)) {
    header('HTTP/1.1 403 Forbidden');
    exit();
}

// Serve the file for download
$filePath = '/path/to/files/' . $_GET['file'];
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
readfile($filePath);

// Function to validate download token against user's session or database record
function isValidDownloadToken($user_id, $token) {
    // Implement your validation logic here
    return true; // Return true if token is valid, false otherwise
}