Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete file after sending to user

I try to send a file to the user with this function

Yii::$app->response->sendFile($tmp_filename, 'test.RData');

Now I want the file to be deleted after sending. I know that there's an event handler for send method in yii/web/Response called EVENT_AFTER_SEND

I tried to access this handler with the following code:

Event::on(\yii\web\Response::className(), \yii\web\Response::EVENT_AFTER_SEND, function ($event) {
          unlink($event->response->filename);  
});

But my problem is

a) I'm not sure if this is the right way

b) how to access the filename inside the event

Any help is appreciated!

like image 530
Sarah West Avatar asked Dec 04 '22 01:12

Sarah West


1 Answers

I had the same problem this week. The documentation says that we can use the $data parameter to add any variable we want on this callback. Here is a example:

Yii::$app->response->sendFile('/path/of/my/temp/file')->on(\yii\web\Response::EVENT_AFTER_SEND, function($event) {
    unlink($event->data);
}, '/path/of/my/temp/file');
like image 115
Clyff Avatar answered Jan 09 '23 14:01

Clyff