N
N
Nikita Stechkin2021-02-20 23:28:52
Laravel
Nikita Stechkin, 2021-02-20 23:28:52

How to deny access to a folder via url?

I need to deny access to public folder via url, how to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2021-02-20
@VAMPIRE37

Another thing.
To prevent files from being accessible by link, you do not need to place them in a public directory.
I did this:
Register the route

Route::get('p/attach/{id}', [AttachmentController::class, 'show'])
  ->name('attachment.show')
  ->middleware(['auth']);

The route is closed by authentication, only registered users can access. But you can arrange any other conditions.
Registering a private drive
// config/filesystem.php
    'private' => [
      'driver'     => 'local',
      'root'       => storage_path('app/private'),
      'visibility' => 'public',
    ],

You can just throw it into an existing local one (local, not public), but I prefer the order.
Further, all downloaded pictures are saved to this disk.
In my case, pictures are attachments and links to them are stored in the database.
We write a method for displaying a pikchi:
// AttachmentController.php
  public function show($id, Request $request, Response $response)
  {
    // Здесь любая логика проверки прав на просмотр файла.
    // ...
    /** @var Attachment $attach */
    $attach = Attachment::findOrFail($id);
    $path = Storage::disk('private')->path($attach->path.$attach->name.'.'.$attach->extension);

    return response()->file($path);
  }

Here we get the attachment identifier from the route, read it and return it in response.
I made a helper to form a link
privateUrl(Attachment $attachment)
  {
    return route('attachment.show', [
      'id'   => $attachment->id,
    ]);
  }

@foreach($files as $attachment)
  <a class="text-underline"
      target="_blank"
      href="{{ privateUrl($attachment) }}"
  >{{ $attachment->original_name }}</a>
@endforeach

PS.
The Attachment class is not part of the framework. This is the model for managing uploaded files.
But in general, I think you understand the principle.

S
Sanes, 2021-02-21
@Sanes

Private files should be in Storage and given by the script.
https://laravel.com/docs/8.x/filesystem#downloadin...

return Storage::download('file.jpg');

return Storage::download('file.jpg', $name, $headers);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question