Как [рекурсивно] Архивировать каталог в PHP?

То средство конструкции объявляет анонимную функцию и сразу выполняет ее. Причина Вы помещаете свой код в теле функции, состоит в том, потому что переменные, которые Вы определяете в нем, остаются локальными для функции и не как глобальные переменные. Однако они все еще будут видимы к закрытиям, определенным в этой функции.

117
задан Alix Axel 15 July 2010 в 17:59
поделиться

2 ответа

Вот простая функция, которая может рекурсивно сжимать любой файл или каталог, требуется только загрузить расширение zip.

function Zip($source, $destination)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

Назовите это так:

Zip('/folder/to/compress/', './compressed.zip');
250
ответ дан 24 November 2019 в 02:05
поделиться

Попробуйте эту ссылку <- БОЛЬШЕ ИСХОДНОГО КОДА ЗДЕСЬ

/** Include the Pear Library for Zip */
include ('Archive/Zip.php');

/** Create a Zipping Object...
* Name of zip file to be created..
* You can specify the path too */
$obj = new Archive_Zip('test.zip');
/**
* create a file array of Files to be Added in Zip
*/
$files = array('black.gif',
'blue.gif',
);

/**
* creating zip file..if success do something else do something...
* if Error in file creation ..it is either due to permission problem (Solution: give 777 to that folder)
* Or Corruption of File Problem..
*/

if ($obj->create($files)) {
// echo 'Created successfully!';
} else {
//echo 'Error in file creation';
}

?>; // We'll be outputting a ZIP
header('Content-type: application/zip');

// It will be called test.zip
header('Content-Disposition: attachment; filename="test.zip"');

//read a file and send
readfile('test.zip');
?>;
2
ответ дан 24 November 2019 в 02:05
поделиться
Другие вопросы по тегам:

Похожие вопросы: