What are some best practices for using PHP to securely link to a PDF file in a protected area of a website?

When linking to a PDF file in a protected area of a website, it is important to ensure that only authorized users can access the file. One way to achieve this is by using PHP to check the user's authentication status before allowing them to download the file. This can be done by verifying the user's session or credentials before serving the PDF file.

<?php
session_start();

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

// Path to the protected PDF file
$pdfFile = 'path/to/protected/file.pdf';

// Serve the PDF file
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . basename($pdfFile) . '"');
readfile($pdfFile);