What are some alternative methods to .htaccess for securing downloads in PHP applications?

Securing downloads in PHP applications is important to prevent unauthorized access to sensitive files. One alternative method to using .htaccess for securing downloads is to use PHP to check for authentication before allowing the download to proceed. This can be done by verifying the user's credentials and permissions before serving the file.

<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    // Redirect to login page or display an error message
    header('Location: login.php');
    exit;
}

// Check if user has permission to download the file
if ($_SESSION['role'] !== 'admin') {
    // Display an error message or redirect to a different page
    echo 'You do not have permission to download this file.';
    exit;
}

// Serve the file for download
$file = 'path/to/file.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
readfile($file);
?>