John Davidson

All files download only through index.php and deny direct access to them from browser


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 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:


$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:

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:

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:

$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));
} 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

3 of 5 based on 3548 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us