没有目录树的Php zip文件

时间:2018-01-11 14:31:08

标签: php

我正在从数组创建脚本压缩文件。

/* creates a compressed zip file */
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;
    }
}

@Mysql connect

$files_to_zip = array();
while($row = mysql_fetch_assoc($shots)) {
 $files_to_zip[] = '/home/username/domains/example.com/public_html/components/items/images/item/' . $row["name"] . '_thb.' . $row["ext"];
}

if(isset($_POST['create'])){

    //if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive5.zip');

}

创建表单提交zip后,文件中有完整的目录树。 如何只压缩没有目录的文件?

第二件事: 当我在总指挥官中打开zip时 - 我可以看到目录和文件。当我正常打开时 - 拉链是空的。

2 个答案:

答案 0 :(得分:0)

addFile()方法的第二个参数是zip中文件的名称。你这样做了:

$zip->addFile($file, $file);

所以你得到的东西是:

$zip->addFile('/path/to/some/file', '/path/to/some/file');

只是将源路径复制到zip中。如果您希望所有文件都在zip中的一个目录中,请从文件名中删除路径:

$zip->addFile($file, basename($file));

这会给你:

$zip->addFile('/path/to/some/file', 'file');

请注意,如果您在不同目录中具有相同名称的文件,这将无法正常工作。

答案 1 :(得分:0)

检查Zip扩展程序的addFile方法上的文档。您可以将本地名称指定为第二个参数。

文档中的示例

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->addFile('/path/to/index.txt', 'newname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>