如何使用PHP压缩整个文件夹

won*_*ana 115 php zip

我在stackoveflow找到了一些关于如何压缩特定文件的代码,但是特定文件夹怎么样?

Folder/
  index.html
  picture.jpg
  important.txt
Run Code Online (Sandbox Code Playgroud)

在里面My Folder,有文件.在压缩之后My Folder,我还要删除文件夹的全部内容important.txt.

堆栈找到这个

我需要你的帮助.谢谢.

Dad*_*dor 291

代码已更新2015/04/22.

压缩整个文件夹:

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

压缩整个文件夹+删除除"important.txt"以外的所有文件:

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

// Initialize empty "delete list"
$filesToDelete = array();

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

        // Add current file to "delete list"
        // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
        if ($file->getFilename() != 'important.txt')
        {
            $filesToDelete[] = $filePath;
        }
    }
}

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

// Delete all files from "delete list"
foreach ($filesToDelete as $file)
{
    unlink($file);
}
Run Code Online (Sandbox Code Playgroud)

  • @alnassre这个问题的要求:"我还想删除除了important.txt之外的文件夹的整个内容".另外,我建议你在执行之前始终阅读代码. (10认同)
  • 在调用`$ zip-> close()`之前删除文件将不起作用.检查我的答案[这里](http://stackoverflow.com/a/21528186/171318) (3认同)
  • 您必须将 dir(此脚本所在的位置)上的 chmod(可写)设置为 777。例如:如果脚本位于 /var/www/localhost/script.php,那么您需要在 dir /var/www/localhost 上设置 chmod 0777 /. (2认同)

Mar*_*ker 51

ZipArchive类中有一个有用的未记录方法:addGlob();

$zipFile = "./testZip.zip";
$zipArchive = new ZipArchive();

if (!$zipArchive->open($zipFile, ZIPARCHIVE::OVERWRITE))
    die("Failed to create archive\n");

$zipArchive->addGlob("./*.txt");
if (!$zipArchive->status == ZIPARCHIVE::ER_OK)
    echo "Failed to write files to zip\n";

$zipArchive->close();
Run Code Online (Sandbox Code Playgroud)

现在记录在:www.php.net/manual/en/ziparchive.addglob.php

  • 是`addGlob`是递归的吗? (5认同)
  • @netcoder - 编写phpt用于测试它的好处...基本上,通过ZipArchive类的源读取,并在那里找到....还有一个未记录的addPattern()方法,采用正则表达式样式模式,但我从来没有设法让它工作(可能是班上的一个错误) (2认同)
  • 另外,如果指定的文件不存在,仅使用“ZipArchive::OVERWRITE”将会失败,因此请使用“(ZipArchive::CREATE | ZipArchive::OVERWRITE)”(假设您想根据需要创建或覆盖)。 (2认同)

net*_*der 19

试试这个:

$zip = new ZipArchive;
$zip->open('myzip.zip', ZipArchive::CREATE);
foreach (glob("target_folder/*") as $file) {
    $zip->addFile($file);
    if ($file != 'target_folder/important.txt') unlink($file);
}
$zip->close();
Run Code Online (Sandbox Code Playgroud)

不会递归拉链.


Kev*_*ead 18

我假设这是在zip应用程序在搜索路径中的服务器上运行.应该适用于所有基于Unix的服务器,我猜大多数基于Windows的服务器.

exec('zip -r archive.zip "My folder"');
unlink('My\ folder/index.html');
unlink('My\ folder/picture.jpg');
Run Code Online (Sandbox Code Playgroud)

之后,存档将驻留在archive.zip中.请记住,文件或文件夹名称中的空格是导致错误的常见原因,应尽可能避免.


Ami*_*man 13

我尝试使用下面的代码,它正在工作.代码是自解释的,如果您有任何问题,请告诉我.

<?php
class FlxZipArchive extends ZipArchive 
{
 public function addDir($location, $name) 
 {
       $this->addEmptyDir($name);
       $this->addDirDo($location, $name);
 } 
 private function addDirDo($location, $name) 
 {
    $name .= '/';
    $location .= '/';
    $dir = opendir ($location);
    while ($file = readdir($dir))
    {
        if ($file == '.' || $file == '..') continue;
        $do = (filetype( $location . $file) == 'dir') ? 'addDir' : 'addFile';
        $this->$do($location . $file, $name . $file);
    }
 } 
}
?>

<?php
$the_folder = '/path/to/folder/to/be/zipped';
$zip_file_name = '/path/to/zip/archive.zip';
$za = new FlxZipArchive;
$res = $za->open($zip_file_name, ZipArchive::CREATE);
if($res === TRUE) 
{
    $za->addDir($the_folder, basename($the_folder));
    $za->close();
}
else{
echo 'Could not create a zip archive';
}
?>
Run Code Online (Sandbox Code Playgroud)


Ali*_*lah 7

这是一个将整个文件夹及其内容压缩为zip文件的函数,您可以像这样简单地使用它:

addzip ("path/folder/" , "/path2/folder.zip" );
Run Code Online (Sandbox Code Playgroud)

功能:

// compress all files in the source directory to destination directory 
    function create_zip($files = array(), $dest = '', $overwrite = false) {
    if (file_exists($dest) && !$overwrite) {
        return false;
    }
    if (($files)) {
        $zip = new ZipArchive();
        if ($zip->open($dest, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        foreach ($files as $file) {
            $zip->addFile($file, $file);
        }
        $zip->close();
        return file_exists($dest);
    } else {
        return false;
    }
}

function addzip($source, $destination) {
    $files_to_zip = glob($source . '/*');
    create_zip($files_to_zip, $destination);
    echo "done";
}
Run Code Online (Sandbox Code Playgroud)


Waq*_*gir 7

使用这个函数:

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 . '/'));
            } elseif (is_file($file) === true) {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    } elseif (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)


归档时间:

查看次数:

201416 次

最近记录:

6 年,8 月 前