I have the following structure in my website :
- index.php
- files(directory) ---> file1.pdf
How can I prevent the direct access to the file (e.g https://example.com/files/file1.pdf) and allow the file to be downloaded from within the displayed web page for login users?
here is the php code for the index which reads the files from the directory:
<?php
include('session.php');
$path = './files';
$files = scandir($path);
$files = preg_grep("/^(\.|\.\.|index\.php|\.htaccess)$|.php$|\.meta\.js$/",scandir($path), PREG_GREP_INVERT);
foreach($files as $file){
echo '<div>';
echo "<a href='$file' >$file</a>";
echo "</div>";
}
?>
My Answer:
file1.jpg
file2.pdf
file3.docx
To prevent direct access to the files in the "files" directory, you can use the following code in your .htaccess file:
Order allow,deny
Deny from all
This code will deny access to any files with the extensions .jpg, .pdf, and .docx in the "files" directory.
Then, in your index.php file, you can create download links for these files like this:
html
Download File 1
Download File 2
Download File 3
In your index.php file, you can then use PHP to handle the file downloads. Here is an example of how you can do this:
php
$filesDirectory = 'files/';
if(isset($_GET['file'])) {
$file = $_GET['file'];
$filePath = $filesDirectory . $file;
if(file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
} else {
echo 'File not found.';
}
}
?>
This code will check if the requested file exists in the "files" directory and then force the browser to download it. This way, users can only access the files through the index.php file and not directly through the browser.
Rate this post
5 of 5 based on 3221 votesComments