Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting files after download in laravel

Tags:

I'm creating a application that lets a user download a file. After the download i want the file to be deleted. The end of my code is like this:

return Response::download(public_path() . '/uploads/_tmp/' . urldecode($filename));

which means that the function ends on the return an i am not able to delete the file. I have tried to call a 'after' filter on the route but then the file gets deleted to quickly.

Any ideas?

like image 869
vincent Avatar asked Oct 10 '14 09:10

vincent


People also ask

How do you delete a file in Laravel?

You could use PHP's unlink() method just as @Khan suggested. But if you want to do it the Laravel way, use the File::delete() method instead. $files = array($file1, $file2); File::delete($files);

How do I delete files from storage folder in Laravel?

One way to delete a file from the public directory in Laravel is to use the Storage facade. To delete a file, you will need to follow the following steps: Step 1: Check to ensure that the folder and file exist. Step 2: Delete the required file.

How do I delete a folder in Laravel?

The deleteDirectory() method from File Facade is used to delete a folder. The files along with the folder are completely removed by this method.


2 Answers

You can use deleteFileAfterSend http://laravel.com/docs/5.0/responses#other-responses

return response()->download($filePath, $fileName, $headers)->deleteFileAfterSend(true);

like image 170
Jon Avatar answered Oct 05 '22 23:10

Jon


I personally use the following;

$response = Response::make(file_get_contents($path_to_file), $status_code, $headers);

Status code is obviously the code which you want to return.

Within the $header parameter you can pass an array with the indexes Content-Type and Content-Disposition.

Then you can simply unlink $path_to_file and return $response.


Much easier way of deleting a file would be to use Jon's answer for versions of Laravel > 4.0.

You can use deleteFileAfterSend http://laravel.com/docs/5.0/responses#other-responses

return response()->download($filePath, $fileName, $headers)->deleteFileAfterSend(true);
like image 37
Matt Burrow Avatar answered Oct 06 '22 01:10

Matt Burrow