John
John

Reputation: 111

Yii2: Where to store uploaded files?

Story:
User should upload some private files to the server. And he should have access to that files, for read(like viewing images or pdf files). I placed them not in web root, so there is no direct link to them. But after the first request, when the server publish them for authenticated user, it becomes available for all others by web/assets/* links.

Question:
Is there a way to clear assets with every request? Or is there a better way to publish private files only for owners?

Upvotes: 1

Views: 648

Answers (1)

Justinas
Justinas

Reputation: 43507

You can request that file by PHP script (sorry, I know only Yii1 syntax):

?r=resources/get&fileName=filename.png

public function actionGet() {
    $fileName = Yii::app()->request->getParam('fileName');
    $filePath = __DIR__.'/../../../files/'.$fileName;
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $fileName);

    if (file_exists($filePath) && Yii::app()->user->canAccess($fileName)) {
        header('content-type: '.$mime);
        header('content-disposition: inline; filename="'.$fileName.'";');
        readfile($file);
    } else {
        $this->redirect('site/index');
    }
}

Upvotes: 3

Related Questions