yii2 php how to dynamically generate download file link for file bigger size like 650 MB

5.1k views Asked by At

I have a website where people will come and they will fill the form and after that they will receive links to download dataset files each of them are of 650 MB. I do not want to use hardcoded paths otherwise my form will not be useful and people will start downloading those files through the hard links.

I am not sure how to generate dynamically random link file with such capability to provide files like 650 MB in size.

1

There are 1 answers

1
jmwierzbicki On

This is a bit of advanced task but not impossible. First off, start with creating database table with fields: id, file_path, hash, active - After that create Active Record model for this table.

Create action in controller for downloading that requires $hash as parameter, and put following logic there:

<?php
public function actionDownload($hash)
{
    $model = FileModel::find()->where(['hash' => $hash])->one();
    if ($model && $model->active == 1) {
        $file          = $model->file_path;
        $model->active = 0;
        $model->save(false);
        return $this->render('download', ['file' => $file]);
    }

    return $this->render('downloadLinkExpired');
}

download view:

<?php
if (file_exists($file)) {
    Yii::$app->response->sendFile($file);
}

Then, in Your form controller generate md5 hash based on current time and maybe some form fields (just to avoid duplicated hash). And for every link, save new model in database. Finally, render links with hash parameter.

Url::toRoute('file/download', ['hash'=>$hash])