S
S
Sergey Bard2018-12-09 13:22:56
Yii
Sergey Bard, 2018-12-09 13:22:56

Why can't I create/download a zip archive?

hello everyone, for a long time I can’t understand what’s wrong, I need to create a temporary archive, add files to it and send it for download, I do it like this

if (!extension_loaded('zip')) {
        return false;
    }  
    $file = tempnam(sys_get_temp_dir(), rand(0, 999999999).'zip');    
    $zip = new \ZipArchive();
    if ($zip->open($file, \ZipArchive::CREATE) !== TRUE) {
        throw new \Exception('Cannot create a zip file');
    }
    foreach($files as $file){
        $zip->addFile($file);
    }
    if(file_exists($zip->filename)){        
        return \Yii::$app->response->sendFile($zip->filename, time().'.zip', ['mimeType'=>'application/zip']);
    } else {            
        throw new NotFoundHttpException('Такого файла не существует '.$file);
    }
    $zip->close();

but all the time it says "This file does not exist", what am I doing wrong?, tell me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Krivosheev, 2018-12-09
@Nemozar

The archive is saved at the time of closing. Move closed ones to file_exists

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question