Skip to content
PHP Logo

How can PHP handle user authentication to access specific PDF files in a secured directory?

To handle user authentication for accessing specific PDF files in a secured directory, you can use PHP sessions to manage user login and access control. Once a user is authenticated, you can check their credentials before allowing access to the PDF files. You can use PHP to read the PDF files from the secured directory and serve them to authenticated users only.

php
<?php
session_start();

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

// Check user credentials before allowing access to specific PDF files
$allowedUsers = ['user1', 'user2']; // Define allowed users
if(!in_array($_SESSION['username'], $allowedUsers)) {
    die('You do not have permission to access this file.');
}

// Serve the PDF file
$filePath = 'secured_directory/file.pdf';
header('Content-Type: application/pdf');
readfile($filePath);