How can PHP be used to offer a file for download without revealing the URL?

When offering a file for download in PHP, it is important to prevent direct access to the file by users who may try to access it without permission. One way to do this is by using PHP to read the file from a secure directory outside of the web root, then outputting the file content to the user without revealing the actual file URL.

<?php
// File to be downloaded
$file = 'path_to_secure_directory/your_file.pdf';

// Set headers to force download and prevent caching
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));

// Read and output the file content
readfile($file);
exit;
?>