Ishaque Javed
Ishaque Javed

Reputation: 406

How to make a public directory restricted in laravel?

I am trying to restrict non loggedin users from downloading contents, what I have uploaded in a public directory.I am currently working on Laravel 5.2. So still now what I have done, I just a make a URL which checks the file name and folder name and download the files. In that way, I am hiding my parent folder directory from users. But this is not a good practice because if anybody finds the file URL then they can access it without logging in.

This is my download script:

public function getFile(Request $request)
{
          *************
          *************
 $folderFilePath = public_path('my file directory');
 return response()->download($folderFilePath, $filename, []);
}

So, is there a way that can restrict downloads from a particular directory for non logged in users in laravel? Thanks a lot in advance.

Upvotes: 6

Views: 941

Answers (2)

Prince Lionel N'zi
Prince Lionel N'zi

Reputation: 2588

You can Assigning Middleware To Route that direct to the getFile method of your controller

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163798

You should keep the files in the storage directory which is not accessible for users. Then these files will be protected and authenticated users will still be able to download them:

if (auth()->check()) { 
    $folderFilePath = storage_path('my file directory');
    return response()->download($folderFilePath, $filename, []);
}

Upvotes: 6

Related Questions