Are there alternative methods in PHP to access files from protected directories without passing credentials in the URL?

When accessing files from protected directories in PHP, passing credentials in the URL is not recommended for security reasons. An alternative method is to use server-side authentication mechanisms such as sessions or tokens to validate the user's access rights before serving the file.

<?php
session_start();

// Check if user is authenticated
if(isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true) {
    // Serve the file from the protected directory
    $file = '/path/to/protected/file.txt';
    
    // Set appropriate headers
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    
    // Output the file content
    readfile($file);
} else {
    // Redirect to login page or show an error message
    header('Location: login.php');
    exit();
}
?>