How can PHP developers implement a secure method to prevent direct linking to files and restrict downloads to only authorized users on their website?

To prevent direct linking to files and restrict downloads to authorized users, PHP developers can implement a secure method by using a combination of server-side validation and session management. One approach is to store files outside the web root directory and create a PHP script to handle file downloads. This script can check if the user is authenticated and authorized to access the file before serving it.

<?php
session_start();

if(isset($_SESSION['authenticated_user'])) {
    $file = '/path/to/secure/file.pdf';
    
    if(file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename=' . basename($file));
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    } else {
        echo 'File not found.';
    }
} else {
    echo 'Unauthorized access.';
}
?>