atif
atif

Reputation: 1693

How to allow only logged in user to access files in a folder on linux server

I created .htaccess file and place this piece of code in it :

Order Deny,Allow
Deny from all

Here is my php code which is working fine on my windows machine with WAMP SERVER on it :

    $path = $data['path']; // complete path to file

if (is_user_logged_in()) {
    //return $path;
    if (file_exists($path)) {
        header('Cache-Control: public');
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Transfer-Encoding: binary');
        readfile($path);
    }
} else {
    return 'Welcome, visitor!';
} 

But when I run it on server, it didn't work at all. There is a locked folder, in which I have placed .htaccess file. And under locked folder there are many subfolders which I want to limit access to only logged in users.

Upvotes: 0

Views: 2775

Answers (2)

Blazej Kita
Blazej Kita

Reputation: 135

I use a another way to download file by loged user (without connect to DB and running all framework...).

First of all, when user is loged a generate special link using: sessionID, pathDir, userId, seprarator "=" and secureKey.

$tx = rand(999,99999).'='.$dirUQ.'='.$user_id.'='.$fileUQ.'='. session_id();        
$checkSum = hash('sha256', $tx.$this->keySecure );        
$sx = $tx.'='.$checkSum;

Thanks for this I get special param, unique for every user using get download file: /download.php?get_sx=91653%3D1%3D1%3D1655104198_9592081.jpg%3D123e2592526883ebfa426898f09c7c9e%3Dec30217a28a564f24dfed226bf3b37b11e0f6a0d732a98a1cfd598dc7cfe2fb2&gofull=600

  1. change you private secure key
  2. generate params "get_sx" for your files
  3. exectue method "downloadIfAuth" in your index.php file

My PHP Class

class FileSecure {
    //put your code here
    
   private $keySecure = '***My_KEY_TO_GEN_LINK';
   private $sessionID = '';
   
   
   public function __construct($get) 
   {
       $this->sessionID = $_COOKIE['PHPSESSID'] ?? '';           
   }
   
   
   /**
    * check if param get_sx added
    */
   public function downloadIfAuth()
   {         
      if(isset($_GET['get_sx']) && $this->sessionID != '')
      {
          
          $tx = $_GET['get_sx'];
          $params = explode('=', $tx);
          
 
          if(count($params) == 6)
          {
              $rand               = $params[0];
              $dirUQ              = $params[1];
              $px_user_id         = $params[2];
              $fileUQ             = $params[3];
              $sessionId          = $params[4];
              $checkSum           = $params[5];
                                  
              $tx2 = $rand.'='.$dirUQ.'='.$px_user_id.'='.$fileUQ.'='. $this->sessionID;        
              $checkSum2 = hash('sha256', $tx2.$this->keySecure );
                        
               if($checkSum == $checkSum2)
               {                                                         
                    $path = 'files/'.$dirUQ.'/'.$fileUQ;                                                            
                    if(file_exists($path))
                    {
                        $type =  @mime_content_type($path);
                     
                        header('Content-type:  '.$type);
                        header('Content-Length: '.filesize($path) );
                        header('Content-Disposition: filename='.$fileUQ );
                        echo file_get_contents($path);                           
                        die;
                    }                                        
               }else
               {          
                   
                   header('Location: /?crc=false');
                   die;
               }
          }                                    
                header('Location: /?crc2=false');
                die;
      } 
   }
    
   
   public function getSX( string $dirUQ, int $user_id, string $fileUQ)
   {
        $tx = rand(999,99999).'='.$dirUQ.'='.$user_id.'='.$fileUQ.'='. session_id();        
        $checkSum = hash('sha256', $tx.$this->keySecure );        
        $sx = $tx.'='.$checkSum;        
        $sx = urlencode($sx);        
        return $sx;
   }
   
}

How to generate link

   $fileSecure = new FileSecure(array());
   $imgs = '<img src="/index.php?get_sx='.$fileSecure->getSX("myHomeDir", $this->getUser()->GetId(), "myFile.jpg").'" class="img_browser"  >

Put below code to you index.php to check if get_sx is exist

 $file = new FileSecure($_GET);
   $file->downloadIfAuth();

The most important thing is "$_COOKIE['PHPSESSID']". When browser execute index.php send cookie. Thanks for this, special sum and secureKey we can download file by loged user. And... we don't need to connect to DB.

If you see any bug in my way, please show me :) Sorry for my english :(

Upvotes: 0

Ian
Ian

Reputation: 2021

Your .htaccess file is a (slow) way to stop anyone requesting your files. It does not care if the user is logged in or not.

The approach I would take is to

a) Move the files you want to give logged in access to out of the root. That way no-one can request the path directly - they have to use your php file to get access.

b) In your php file, test if your user is logged in. If not, present them with the log-in screen or error message as appropriate.

c) As they are logged in read the file you want to show them and echo the contents, (or read the data and build the reply page).

Upvotes: 1

Related Questions