NO uses la carpeta public para el upload de ciertos archivos, protege tus archivos en la storage en Laravel

La descarga de archivos es una característica común en el desarrollo de software, poder permitir la descarga de determinados archivos en base a algún control interno determinado por las reglas de negocio de tu aplicación, es un proceso común, por ejemplo, la venta de archivos que tengas alojados en la aplicación y que una vez adquirido por el usuario, el mismo puede descargarlo, para eso, desde la aplicación, verificamos el pago y a posterior permitimos la descarga.

Lo importante de notar aquí es que, los archivos no pueden estar alojados en la aprieta public, como si fueran una imagen cargada por el proceso de upload como hicimos antes, ya que,cualquier persona que sepa cual es el nombre del archivo pudiera acceder a él.

Recordemos que en un proyecto en Laravel, la única carpeta que es accedida de manera pública es justamente la carpeta public, por lo tanto, para estos archivos que queramos controlar el acceso no es recomendado emplear esta carpeta.

Podemos subir archivos en cualquier carpeta de la aplicación, no solamente la carpeta public, lo cual es particularmente útil para estos escenarios en donde queremos controlar el acceso a estos archivos, por ejemplo, la carpeta de storage; creamos un disco en consecuencia:

config\filesystems.php

'files_sell_uploads' => [
  'driver' => 'local',
  'root' => app()->storagePath()
],

La carga del archivo sería algo como:

function uploadBook()
{
   $this->rules = [
       'fileBook' => 'nullable|mimes:epub,pdf|max:20024'
   ];

   $this->validate();

   if ($this->fileBook) {
       $name = time() . '.' . $this->fileBook->getClientOriginalExtension();
       $this->fileBook->storeAs('book', $name, 'files_sell_uploads');

       YourModel::create([
           'file' => $name,
           'type' => $this->fileBook->getClientOriginalExtension(),
           ***
       ]);

   }
}

Y en este ejemplo, te muestro en base a alguna condición que debe de cumplir el usuario:

if ($filePayment && $file)

Y poder descargar el archivo:

Storage::disk('files_sell_uploads')->download('book/' . $file->file, "book." . $file->type);

Es importante aclarar que la única forma de acceder a estos archivos mediante el canal http seria mediante la función anterior, al ser la carpeta de storage una carpeta que no se puede acceder de manera pública, la única forma que tiene un usuario para acceder a estos archivos es que nosotros implementemos una capa de acceso como la función anterior.

En definitiva, el esquema presentado anteriormente es estupendo si quieres desarrollar alguna tienda en línea sobre tu aplicación en donde los archivos a vender se encuentren almacenados en la misma aplicación.

public function downloadFile(File $file)  //show
{
   $user = auth()->user() ?? auth('sanctum')->user();

   $filePayment = FilePayment::where(***)->first();

   $file = File::where(***)->first();

   if ($filePayment && $file) {
       // return  Storage::disk('files_sell_uploads')->download('book/1724355661.pdf');
       return  Storage::disk('files_sell_uploads')->download('book/' . $file->file, "book." . $file->type);
   }

   return response()->errorResponse("", 403, 'Producto no adquirido o no existe');
}

Transcripción del vídeo

I wanted to quickly show you an implementation that I find very interesting that we have here in Laravel Although you can really take it to any framework here it is important to know how these types of frameworks work especially those based on php which only have one folder with public access everything else is protected and this is important because we can take advantage of it for what I want to show you in this video which is to be able to host files through an unload process for example which we already know in a protected way so here I show you a little bit what the implementation is Obviously I already have the Download process here Ill see if I can find it here quickly Control p Book and it would be this one Well you can see that I develop my project freely and use it here Im going to go down a bit and one day Ill find the can part here Look its the process that Ive taught you that I always follow in the course in which once we have the object here then we start to work with it a little bit In this case it is to create a file here Well there are some as they say some models that may not come as much as the case But the important thing is the process Download that I have here in a file called fileBook and really little more to say here you can see that it is the normal process and we store it in some location that is as always I show you that it is using one of the disks this disk unlike what we always use which is the public folder and that is why I began indicating to you Well what was commented that we can store files in any other location usually we do it from the public folder but in this case I am accessing is the Store pad why the hell am I doing this because this implementation that I am showing you is for the sale of books that I have here in desarrollolibrenet So I explain this to you because surely if you implement an application in Laravel you will surely want to have files that are not accessed publicly since the problem with this folder is that it is precisely public therefore anyone can access it regardless of whether they have or the URL since if they know what the name and the file and the location are even if you do not want to give them access is simply come here I am going to show it to you here quickly all these images that appear here are in the public folder so if I right click here to see open image a new tab here you can see that it is accessing them because again they are in a public folder which would be in my case the one I have here public image example well and here follow the location and Ah you have the image but if you are selling a resource with my case a book or it is simply a management type application in which you have some excels or something like that important that you do not want to be accessed by anyone who has access to that application you do not want you want them to be protected that is to say you want what is important based on certain business rules in my case is that the user has bought the book can access them obviously again you cannot do this if the folder is public of course you can hide the image That is to say you can hide the resource and give it a strange name based on time something like that But you can always access it regardless of whether it is showing it is listing it as me in a public way In this case by an image or it is protected For example if I had access copy URL relative so that you understand a little what I am indicating I am going to copy all this from example Note that it is from here I example that I placed it twice Well in the other Slashes lets see if I can I can I can it should appear there It is there You see That is to say I am accessing a resource in a public way and if you have a file for example a PDF here it will appear if you have an Excel here it will know Download etcetera because you are accessing the same one

So at this point I hope it has at least become clear that if you want to protect certain files either because they are an online store as in my case or because they are part of some accounting files or something like that you cannot store them in this folder because again you can access them regardless of what you implement here in your project in Laravel and that is why I used protected folders as they are any other than the public one In this case I wanted to use the storage one which is where I store the books and here are all the books How do I access them Well based on a simple function which is the one found here which is the one that leads to the end when a person buys a book from me I come here login here I am I am in my books I for example have this well what

- Andrés Cruz

In english

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz En Udemy

Acepto recibir anuncios de interes sobre este Blog.

!Cursos desde!

10$

En Udemy

Quedan 2d 14:13!


Udemy

!Cursos desde!

4$

En Academia

Ver los cursos

!Libros desde!

1$

Ver los libros
¡Hazte afiliado en Gumroad!