Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sibiria's avatar

File not deleted after beginning send response and break the connect

I have next code in action

$zip = $someService->generateZip();

return response()->download($zip)->deleteFileAfterSend();

But if the client breaks the connect file not will be removed. How I can fix this behavior?

0 likes
3 replies
Jaytee's avatar
Jaytee
Best Answer
Level 39

Of course it wouldn't. If the user closes the browser before the download has finished, the download will be cancelled, thus it won't be deleted.

You could check if a current ZIP exists, if it does, allow the user to download that zip, without generating another one, and then delete it.

If it doesn't exist, create it, and then allow them to download it. Then delete it.

Could also run a Job which deletes ZIPs after a certain amount of time.

denvit's avatar

I do agree with @jaytee comment. The only thing that I will change, is the logic around files.

I will set a time limit for downloading a file - x days/hrs and then I'll set up a job that will check for example every x hrs or once a day if there's any file (zip) that is older than x day/hrs and if it is, then delete it.

This is a much better approach in my opinion because you don't have to care if user cancel (breaks) the download process in the browser.

Sibiria's avatar

I had such a strategy. Until Google began to sort out the download links and the server did not run out of free space. After that I had to review the business process and prohibit downloading not for an authorized user

Please or to participate in this conversation.