What are some alternative methods for generating links to files for sharing in PHP, considering the limitations of file paths in browsers?

When sharing files in PHP, the direct file paths may not work due to browser limitations or security concerns. One alternative method is to use a script to read the file and output its contents, while keeping the actual file path hidden. This way, users can access the file through a generated link without exposing the file's location.

<?php
// File to be shared
$file = 'path/to/file.pdf';

// Check if file exists
if (file_exists($file)) {
    // Set appropriate headers
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="' . basename($file) . '"');
    header('Content-Length: ' . filesize($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    // Read the file and output its contents
    readfile($file);
    exit;
} else {
    echo 'File not found.';
}
?>