如何[递归]在PHP中压缩目录?

ed2*_*209 117 php directory recursion zip directory-structure

目录是这样的:

home/
    file1.html
    file2.html
Another_Dir/
    file8.html
    Sub_Dir/
        file19.html
Run Code Online (Sandbox Code Playgroud)

我使用PHPMyAdmin中使用的相同PHP Zip类http://trac.seagullproject.org/browser/branches/0.6-bugfix/lib/other/Zip.php.我不确定如何压缩目录而不仅仅是文件.这是我到目前为止所拥有的:

$aFiles = $this->da->getDirTree($target);
/* $aFiles is something like, path => filetime
Array
(
    [home] => 
    [home/file1.html] => 1251280379
    [home/file2.html] => 1251280377
    etc...
)

*/
$zip = & new Zip();
foreach( $aFiles as $fileLocation => $time ){
    $file = $target . "/" . $fileLocation;
    if ( is_file($file) ){
        $buffer = file_get_contents($file);
        $zip->addFile($buffer, $fileLocation);
    }
}
THEN_SOME_PHP_CLASS::toDownloadData($zip); // this bit works ok
Run Code Online (Sandbox Code Playgroud)

但是当我尝试解压缩相应的下载zip文件时,我得到"不允许操作"

这个错误只发生在我尝试解压缩我的mac时,当我通过命令行解压缩文件解压缩时.我是否需要在下载时发送特定的内容类型,目前为'application/zip'

Ali*_*xel 250

这是一个简单的函数,可以递归地压缩任何文件或目录,只需要加载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();
}
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

Zip('/folder/to/compress/', './compressed.zip');
Run Code Online (Sandbox Code Playgroud)

  • 我想知道为什么这是使用`file_get_contents`并添加字符串.不支持zip直接添加文件? (5认同)
  • 工作得很好,我唯一的问题是我的脚本从不同的位置运行到要压缩的文件,因此当我提供第一个参数时,在zip中使用完整的文件路径位置,如下所示:C:\ wamp\www\export\pkg-1211.191011\pkg-1211.191011.zip,该完整嵌套文件夹结构位于新存档内.有没有办法让上面的脚本只包含我指向的文件和目录,而不是它们来自的完整路径? (4认同)
  • @Danjah:我已经更新了代码,现在应该适用于*nix和Windows. (4认同)
  • 当然,你必须用`DIRECTORY_SEPARATOR`替换所有`'/'`以使它在Windows上运行.否则,您将最终获得ZIP中的完整路径(包括驱动器名称),例如`C:\ Users\...`. (4认同)
  • 原始代码被破坏并且是多余的.没有必要用`\`替换`//`,因为这实际上打破了Windows上的foreach.如果您使用内置的"DIRECTORY_SEPARATOR",则无需更换.`/`的硬编码是导致一些用户遇到问题的原因.我有点困惑,为什么我得到一个空档案.我的修订版将在*nix和Windows下正常运行. (3认同)
  • 这是有效的,只是它正在创建一个以我的 Windows 计算机上的 /root 驱动器为根的文件夹结构。我修改了它来解决问题并使用 DIRECTORY_SEPARATOR 代替。[这是代码。](http://pastebin.com/1dqbzAQx) (2认同)

Gio*_*esi 15

另一个递归目录树归档,作为ZipArchive的扩展实现.作为奖励,包括单语句树压缩助手功能.支持可选的localname,与其他ZipArchive函数一样.处理要添加的代码时出错...

class ExtendedZip extends ZipArchive {

    // Member function to add a whole file system subtree to the archive
    public function addTree($dirname, $localname = '') {
        if ($localname)
            $this->addEmptyDir($localname);
        $this->_addTree($dirname, $localname);
    }

    // Internal function, to recurse
    protected function _addTree($dirname, $localname) {
        $dir = opendir($dirname);
        while ($filename = readdir($dir)) {
            // Discard . and ..
            if ($filename == '.' || $filename == '..')
                continue;

            // Proceed according to type
            $path = $dirname . '/' . $filename;
            $localpath = $localname ? ($localname . '/' . $filename) : $filename;
            if (is_dir($path)) {
                // Directory: add & recurse
                $this->addEmptyDir($localpath);
                $this->_addTree($path, $localpath);
            }
            else if (is_file($path)) {
                // File: just add
                $this->addFile($path, $localpath);
            }
        }
        closedir($dir);
    }

    // Helper function
    public static function zipTree($dirname, $zipFilename, $flags = 0, $localname = '') {
        $zip = new self();
        $zip->open($zipFilename, $flags);
        $zip->addTree($dirname, $localname);
        $zip->close();
    }
}

// Example
ExtendedZip::zipTree('/foo/bar', '/tmp/archive.zip', ZipArchive::CREATE);
Run Code Online (Sandbox Code Playgroud)


use*_*515 10

我编辑了Alix Axel的答案,采取第三种方法,当设置第三个argrument时,true所有文件都将添加到主目录下,而不是直接添加到zip文件夹中.

如果zip文件存在,则文件也将被删除.

例:

Zip('/path/to/maindirectory','/path/to/compressed.zip',true);
Run Code Online (Sandbox Code Playgroud)

第三个argrument true拉链结构:

maindirectory
--- file 1
--- file 2
--- subdirectory 1
------ file 3
------ file 4
--- subdirectory 2
------ file 5
------ file 6
Run Code Online (Sandbox Code Playgroud)

第三个argrument false或缺少zip结构:

file 1
file 2
subdirectory 1
--- file 3
--- file 4
subdirectory 2
--- file 5
--- file 6
Run Code Online (Sandbox Code Playgroud)

编辑代码:

function Zip($source, $destination, $include_dir = false)
{

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

    if (file_exists($destination)) {
        unlink ($destination);
    }

    $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);

        if ($include_dir) {

            $arr = explode("/",$source);
            $maindir = $arr[count($arr)- 1];

            $source = "";
            for ($i=0; $i < count($arr) - 1; $i++) { 
                $source .= '/' . $arr[$i];
            }

            $source = substr($source, 1);

            $zip->addEmptyDir($maindir);

        }

        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();
}
Run Code Online (Sandbox Code Playgroud)