qwertyzw qwertyzw - 6 months ago 28
PHP Question

Lumen callback on completed download

I created a download route from which my client successfully downloads the file by adding the following code to /app/Http/routes.php:

$app->get('/dl', function() use ($app){
return response()->download(getcwd() . "/targetfile");

but now I'd like to somehow have a callback be executed once the file transfer has been complete for a given instance of the get request. How would I do that?

To be a little more specific I'm trying to delete the file once it has been downloaded but this doesn't work:

$app->get('/dl', function() use ($app){
unlink(getcwd() . "/targetfile");
return response()->download(getcwd() . "/targetfile");


Answer to original Question

So in order to have a 'callback' once a response has been sent you use a so-called 'terminable' middleware.

In order for a middleware to be terminable:

1) it has to be global; I.E registered with the middleware function instead of the routeMiddleware


2) It has to have the method 'terminate ($request, $response)' this is the method that will be called once the response has been sent.

public function terminate($request, $response)
    // your code here

An alternative

A global middleware seems to be like a waste of computation resources as it's called for every request/response pair so instead I just looked through Lumen's code to find that the download method is actually returning an instance of


On which I called


Which served my original goal

return response()->download(getcwd() . "/targetfile")->deleteFileAfterSend(true);