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;
?>
Keywords
Related Questions
- How can CSS be utilized in conjunction with PHP to dynamically set background colors based on date comparisons?
- How can PHP beginners ensure the security and integrity of their code when implementing email functionality in their projects?
- What are best practices for reading, modifying, and saving text files with character conversions in PHP?