skip to Main Content

I want to store files in non-public storage folder and I want to display in a front. It would be security against unauthorized access. I know that I can use readfile function but it doesn’t work, for example:

readfile('/private/something.jpg')

Could you show me code or other method to display file from non-public storage folder?

2

Answers


  1. Use the disk method on the Storage facade to specify the disk you want to use.

    you can use the following code:

    $fileContents = Storage::disk('local')->get('my_directory/file.txt');
    

    Note that you have to specify the disk you want to use, as by default Laravel uses the public disk which allows access to public files.

    Login or Signup to reply.
  2. In Laravel, you can store files in a non-public storage folder and display them securely on the front end by using the Storage facade.’

    step-by-step guide:
    Step 1 : we’re creating a new disk named "private" that will store files in a non-public directory located at storage/app/private. We’re also setting the visibility to "private" so that the files will not be directly accessible from the web.

    'disks' => [
        // ...
        'private' => [
            'driver' => 'local',
            'root' => storage_path('app/private'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'private',
        ],
    ],
    

    Step 2 :
    Store the file using the putFileAs() method:

    $file = $request->file('file');
    $path = $file->storeAs('private', $file->getClientOriginalName(), 'private');
    

    Step 3 :
    Generate a temporary URL for the file:

    $url = Storage::disk('private')->temporaryUrl($path, now()->addMinutes(10));
    <a href="{{ $url }}">Download File</a>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search