Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to zip folder in laravel 5?

need some help for laravel zip file. i have a folder in the public folder and i would like to create a zip of that folder (temp_file folder) whenever the user clicks the button.

public function testing()
{
    $public_dir = public_path('temp_file/');
    $zipFileName = 'myZip.zip';
    $zip = new ZipArchive;

    if ($zip->open($public_dir . '/' . $zipFileName, ZipArchive::CREATE) === TRUE) {
        $zip->addFile('file_path', 'file_name');
        $zip->close();
    }

    $headers = array('Content-Type' => 'application/octet-stream');

    $filetopath = $public_dir . '/' . $zipFileName; 
}

but it seems that it is not creating the zip file and i can't download it. Please need some help

like image 995
needhelp Avatar asked Aug 02 '17 01:08

needhelp


1 Answers

Many people may not know this but ZipArchive::addFile() and ZipArchive::close() also return a boolean to show their success (or failure). You should always check them because only the close method returns if the folder isn't writeable.

Then you said that nothing downloads if you call the controller action. That's right. You didn't tell the program to stream something to the client. You just set two variables, one for headers? and the other one for the exact same file path used above to open the zip file.

The following code is a working example (at least in a configured environment with correct folder permissions) how this procedure can work and get you some "inspiration" for your task.

public function testing()
{
    // Create a list of files that should be added to the archive.
    $files = glob(storage_path("app/images/*.jpg"));

    // Define the name of the archive and create a new ZipArchive instance.
    $archiveFile = storage_path("app/downloads/files.zip");
    $archive = new ZipArchive();

    // Check if the archive could be created.
    if (! $archive->open($archiveFile, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
        throw new Exception("Zip file could not be created: ".$archive->getStatusString());
    }

    // Loop through all the files and add them to the archive.
    foreach ($files as $file) {
        if (! $archive->addFile($file, basename($file))) {
            throw new Exception("File [`{$file}`] could not be added to the zip file: ".$archive->getStatusString());
        }
    }

    // Close the archive.
    if (! $archive->close()) {
        throw new Exception("Could not close zip file: ".$archive->getStatusString());
    }
    
    // Archive is now downloadable ...
    return response()->download($archiveFile, basename($archiveFile))->deleteFileAfterSend(true);
}
like image 170
Dan Avatar answered Sep 20 '22 04:09

Dan