Home > Software design >  how to give access for downloading a file when user is logged in
how to give access for downloading a file when user is logged in

Time:11-18

I have some .zip files in a subfolder which are downloadable by a user when he is logged in. To prevent downloading these files for users which are not logged in ( and know the path to a certain zip file), i use this code in .htaccess

<FilesMatch "\.(zip)$">
  Order Allow,Deny
  Deny from all
</FilesMatch>

The problem is: if a user is logged in, he is also blocked from downloading the file

How can i gave access to the file if logged in and block the file from downloading if not logged in?

per example a zip file is stored in : www.mydomain.com/data/downloads/download.zip

CodePudding user response:

Serve the file via PHP and you can check using the PHP session if the user is logged in.

Could do something like this... (Obviously setting something suitable in the session when you log a user in):

<?php
    session_start();
    if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
        // or however you get the path
        $yourfile = "/path/to/" . $_GET['file']. ".zip";
    
        $file_name = basename($yourfile);
    
        header("Content-Type: application/zip");
        header("Content-Disposition: attachment; filename=$file_name");
        header("Content-Length: " . filesize($yourfile));
    
        readfile($yourfile);
        exit;
    } else {
        echo "Please log in first.";
    }
?>

Obviously you can pass the filename as a querystring parameter and use that in $yourfile to serve the appropriate file. If doing this, which is the correct way to do so, can do some check to ensure the file exists before you serve it.

Example useage would then look like: download.php?file=file1.zip

The above example assumes you are not using any frameworks (i.e. Laravel, CakePHP etc), if you are using a framework, I would advise to use the session objects/functions avaiable.

It is also best practice to store files outside the webroot, this way you will ensure their protection. But this will also work in your case, just set $yourfile to the absolute path to /data/downloads. Doing this you do not need the .htaccess stuff.

  • Related