Download file and delete - Best approach


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



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