What are some best practices for using PHP to handle user authentication and access control in a download area?

When handling user authentication and access control in a download area using PHP, it is important to verify the user's credentials before allowing them to access the files. One common approach is to use sessions to store user authentication information and check it on each page load. Additionally, it is crucial to properly sanitize user input to prevent SQL injection attacks and validate user permissions before allowing file downloads.

<?php
session_start();

// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Check user permissions for downloading files
if($_SESSION['role'] != 'admin') {
    echo "You do not have permission to access this page.";
    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);
?>