Как заархивировать всю папку в PHP, даже пустые? - PullRequest
0 голосов
/ 30 апреля 2019

Я пытаюсь загрузить zip из папки, которая у меня есть в приложении (Laravel 5.8), она работает, но они пропускают все пустые папки, и мне нужны они в zip.

Я уже попробовал ZipArchive (php) и chumper / zipper от композитора.

Есть идеи, как мне это сделать?

Это сервер Linux, работающий под управлением MySQL 5, PHP 7.2 и Apache2.

$files = glob($folder_path);
\Zipper::make($folder_path.'/'.$folder_main_name.'.zip')->add($files)->close();

Эта библиотека принимает только glob, но если у вас есть какое-либо решение, которое работает, я могу легко отказаться от этого.

1 Ответ

0 голосов
/ 30 апреля 2019
// 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)
{
    // Is this a directory?
    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);
    }
    else {
        $end2 = substr($file,-2);
        if ($end2 == "/.") {
           $folder = substr($file, 0, -2);
           $zip->addEmptyDir($folder);
        }
    }
}

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

** Попробуйте это. Вне головы, не проверено. Но это общая идея.

...