Working with encrypted files in Laravel (how to upload a decrypted file)

In my webapp, users can upload files. Before saving and saving the contents of the file are encrypted using the following:

Crypt::encrypt(file_get_contents($file->getRealPath())); 

Then I use the file system that comes with Laravel to move the file

 Storage::put($filePath, $encryptedFile); 

I have a table to store information about each file with columns such as:

  • ID
  • file_path
  • file name
  • original_name (includes extension)

Now I want the user to be able to download this encrypted file. However, I had problems decrypting the file and returning it to the user. The section on the answer file in the Laravel documentation files suggests doing this:

 return response()->download($pathToFile, $name, $headers); 

He wants the file path to be perfect, but at what point can I decrypt the contents of the file so that it is really readable?

I really can do this:

 $encryptedContents = Storage::get($fileRecord->file_path); $decryptedContents = Crypt::decrypt($encryptedContents); 

... but I do not know how to return it as a download with the specified file name.

+5
php file-upload encryption laravel laravel-5
Jan 6 '16 at 1:16
source share
1 answer

You can manually create an answer like this:

 $encryptedContents = Storage::get($fileRecord->file_path); $decryptedContents = Crypt::decrypt($encryptedContents); return response()->make($decryptedContents, 200, array( 'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($decryptedContents), 'Content-Disposition' => 'attachment; filename="' . pathinfo($fileRecord->file_path, PATHINFO_BASENAME) . '"' )); 

You can check the Laravel API for more information on the parameters of the make method. The pathinfo function pathinfo also used to extract the file name from the path, so it sends the correct response file name.

+8
Jan 6 '16 at 1:35
source share



All Articles