Sasha
Sasha

Reputation: 8705

Yii2 - rename file on upload if the file with the same name exist

How can I rename file if the file with the same name exist (prevent overwrite)? This method is used for uploading file:

// Upload user avatar
    public function upload()
    {
        if ($this->validate()):

            $this->avatar->saveAs('../web/images/avatars/' . $this->avatar->baseName . '.' . $this->avatar->extension);
            return true;

        endif;

        return false;
    }

Upvotes: 1

Views: 2013

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133370

Test if file exists with php function and then assign a proper name to your file:

$cnt = 1;
while (file_exists(string $filename)) {
    $filename =  $this->avatar->basename . $cnt; 
    $cnt++;
}

Then save.

Upvotes: 3

Related Questions