5

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!

2 Answers 2

16

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');
1
  • Thanks for this hint, I will definitively try this out!
    – Sarah West
    Jan 31, 2016 at 18:21
3

If you will send the file immediately, you could

header('....');
echo file_get_contents(path/of/file)
unlink(path/of/file);

You could think to create a temporary file, so the operative system will delete it.

1
  • Thanks for your answer! This was my plan b. Thought I could make it the yii way ;-)
    – Sarah West
    Dec 12, 2015 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.