What are some best practices for sharing files with non-users on a PHP website?

When sharing files with non-users on a PHP website, it is important to ensure that the files are not accessible to unauthorized users. One way to achieve this is by using a PHP script to handle the file downloads. This script can check if the user is authenticated before allowing the download to proceed. Additionally, it is recommended to store the files outside of the web root directory to prevent direct access.

<?php
// Check if user is authenticated
if($user_authenticated) {
    // Path to the file
    $file_path = '/path/to/file.pdf';

    // Set headers for file download
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="file.pdf"');

    // Output the file
    readfile($file_path);
} else {
    // Redirect to login page or display an error message
    header('Location: login.php');
}
?>