php压缩同一目录下的所有文件和文件夹

时间:2014-06-27 18:13:40

标签: php zip

如何使用php zip压缩同一目录中的所有文件和文件夹?

所以基本上我有一个文件和文件夹的列表,并希望用PHP压缩所有内容。对不起我不熟悉php zip和php net上的文档没什么帮助

1 个答案:

答案 0 :(得分:0)

您可以使用此功能制作文件的zip文件夹:

public 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将包含所有文件数组。并且$destination将是您在服务器上压缩文件位置。