【问题标题】:How to Exclude Certain Folders from being added to zip generated by php如何排除某些文件夹被添加到 php 生成的 zip
【发布时间】:2017-02-11 13:51:09
【问题描述】:

我想排除某些文件(例如 index.php)被添加到由下面的代码生成的 zip 中。我尝试了一些方法,但都没有奏效。 请看穿并帮助我。

$dir = './archive/';
$zip_file = 'All-file.zip';

// Get real path for our folder
$rootPath = realpath($dir);

// Initialize archive object
$zip = new ZipArchive(); 
$zip->open($zip_file, 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();

header('Content-Description: File Transfer'); 
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);

【问题讨论】:

    标签: php filter directory ziparchive recursiveiterator


    【解决方案1】:
    $exclusions=array('index.php');  // add more filenames to exclusion array as needed
    foreach($files as $name=>$file){
        // only process non-directories && non-excluded files
        if(!$file->isDir() && !in_array($file->getFilename(),$exclusions)){
            $filePath = $file->getRealPath();  // Get real and relative path for current file
            $relativePath = substr($filePath, strlen($rootPath) + 1);
            $zip->addFile($filePath, $relativePath);  // Add current file to archive
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      相关资源
      最近更新 更多