ZipArchive Multile文件/文件夹

时间:2016-12-31 17:37:05

标签: php zip directory hierarchy

我在根目录中有三个文件hash_a.phphash_b.php/morefiles/hash_c.php

我想将其压缩到客户端并对其进行流式处理,但不是以这种方式。

我想向客户端发送类似

的内容

FILE.ZIP

root
|_folder1
  |_a.php 
  |_b.php
  |_c.php

是否可以使用php?

1 个答案:

答案 0 :(得分:0)

首先,您需要创建一个类似下面代码的函数。并将所有文件传递给该函数。

function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) && !$overwrite) { return false; }
    //vars
    $valid_files = array();
    //if files were passed in...
    if(is_array($files)) {
        //cycle through each file
        foreach($files as $file) {
            //make sure the file exists
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    //if we have good files...
    if(count($valid_files)) {
        //create the archive
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        //add the files
        foreach($valid_files as $file) {
            $zip->addFile($file,$file);
        }
        //debug
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

        //close the zip -- done!
        $zip->close();

        //check to make sure the file exists
        return file_exists($destination);
    }
    else
    {
        return false;
    }
}

创建功能后。将文件传递给您需要压缩的功能。代码看起来像这样。

$files_to_zip = array(
    'preload-images/1.jpg',
    'preload-images/2.jpg',
    'preload-images/5.jpg',
    'kwicks/ringo.gif',
    'rod.jpg',
    'reddit.gif'
);
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');

此代码将使.Zip文件包含您需要的文件。