Asha
Asha

Reputation: 913

why does the zip folder is not created with PHP

I'm trying to make a existing folder to a zip and download it using php. The existing folder contain some files. This is my code

$folder = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']';
$zip_name = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.'].zip';

$zip = new ZipArchive; 

if($zip -> open($zip_name, ZipArchive::CREATE ) === TRUE) { 

    $dir = opendir($folder); 

    while($file = readdir($dir)) { 
        if(is_file($folder.$file)) { 
            $zip -> addFile($folder.$file, $file); 
        } 
    } 
    $zip ->close(); 
} 

But when i called the API zip folder is not created. Please go through my code and help me to solve it. Thanks in advance

Upvotes: 1

Views: 66

Answers (2)

Umar Abdullah
Umar Abdullah

Reputation: 1290

Try below code.

$folder = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']';
$zip_name = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.'].zip';

$zip = new ZipArchive; 

$zip->open($zip_name, ZipArchive::CREATE);
foreach (glob($folder) as $file) {
    $zip->addFile($file);
}
$zip->close();

Upvotes: 0

Atif
Atif

Reputation: 64

    // Get real path for our folder
    $rootPath = realpath('folder-to-zip');

    // Initialize archive object
    $zip = new ZipArchive();
    $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

    // Create recursive directory iterator
    /** @var SplFileInfo[] $files */
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($rootPath),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file)
    {
        // Skip directories (they would be added automatically)
        if (!$file->isDir())
        {
            // Get real and relative path for current file
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($rootPath) + 1);

            // Add current file to archive
            $zip->addFile($filePath, $relativePath);
        }
    }

    // Zip archive will be created only after closing object
    $zip->close();

Upvotes: 1

Related Questions