Download file and delete - Best approach

Hi
I have setup a download to a pdf file via a file handle and then write it out as follows ( with some suitable headers )

$stream = new \Slim\Http\Stream($fh);

$response = $response->withBody($stream);

/* cannot delete / unlink here */

return $response;

however I want to delete the file but can’t as the response needs it.

I’m not sure the best approach here ?

  1. scheduled a task to delete the file
  2. find a different way to write to the response so that the file can be deleted
  3. middleware?

any help much appreciated

Steve

Instead of streaming the file, you could read the whole file’s contents into memory, then delete it, then return it.

Once it’s attached to the body via file_get_contents() or something similar you can safely delete the file.

fab thanks
they both sound useful options

Hi guys,

I’m kinda working on something similar and I can’t make it work. How do you attach the file using file_get_contents to the response body so the user can download it?

It depends on the file / mime type and other parameters.

Examples:

Thanks for the quick response.

My files are mp3 / mp4 I have no issue with the downloading part using Stream but my problem is how to delete the file after the user download it. I’m not sure how to store it in memory so I can safely delete the file while the user is still downloading it without interruption.

This is my solution:

https://paste.sr.ht/~fabrixxm/0c5a706cd77ac2d64f4fed84cf35f3530f7a43ca