0

I have a site for articles applications.

I need to deny all direct access to these files but allow the download on certain pages. These files are .pdf

The location of the files is: "./public_html/files"

Is there a way to deny all direct access to these files, but allow the download from specific buttons?

1 Answer 1

2

You must implement a wrapper on top of your file system and add extra security for this purpose like token.

Let's say your route for downloading is:

<BASE_URL>/download/{x}

and x is name of the file. This route will only return the file content from ./public_html/files if user provided a valid token in url like:

<BASE_URL>/download/{x}?token=diji12jidj

All of the implementation of this method depends on your needs, e.g. token can be based on user session or based on time or ...

Here is a simple hint in php:

// First page
session_start();

$_SESSION['download_key'] = random_string() // a function that you can implement in anyway you want

// In you html
<a href="download.php?name=<FILE_NAME>&download_key=<?= $_SESSION['download_key'] ?>">Download here</a>


// File: download.php
if(isset($_SESSION['download_key']) && $_REQUEST['download_key'] == $_SESSION['download_key']) {
    // find file 
    $path = ... // path to file
    $fp = fopen($path, 'rb');

    // send the right headers
    header("Content-Type: image/png"); // or anything else
    header("Content-Length: " . filesize($path));

    
    fpassthru($fp);
    exit;
}
4
  • How can I do that? Can you send me a video or article about "wrapper on file system"? IDK what is that. Jan 2, 2022 at 11:36
  • 1
    it's not anything special. What's your backend language? Jan 2, 2022 at 11:59
  • Sorry, I'm starting.I'm using PHP. Jan 2, 2022 at 14:05
  • Ok. So you must develop a script in php to do it. You can use free file sharing scripts or simply you can develop it yourself. I can't explain all aspects for you but I'll give you a simple solution(not perfect). Check my answer I'll update it Jan 3, 2022 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.